How to define a struct in C

Structures (or structs) in C are something like “mini-objects”: they are wrappers around multiple variables, much like the properties of an object. Since plan C doesn’t have objects, these are as close as it gets to them, and they can be quite helpful. Apple uses them extensively (think of a CGRect for example), and it’s easy to build our own.

Here’s how we can do that.

Creating a struct

We can define a struct like this:

    // define a struct
    struct cube {
        int length;
        int width;
        int height;

Here we create a struct with the name of cube and define three variables inside it. They don’t have to be of the same type, you can mix and match int, float, char and all the rest of the merry gang. The variables of a struct are called members.

When defined, a struct can be seen as a template. To use it, we need to initialise a new instance of the struct and populate the member variables, like so:

    // initialilze our struct
    struct cube massiveCube;

    // and populate it with values
    massiveCube.length = 5;
    massiveCube.width = 5;
    massiveCube.height = 7;

Our instance of the struct is called massiveCube, and we can refer to its member variables by dot notation.

The whole setup can be done in one step too, like this:

    // or define and init
    struct oval {
        int width;
        int height;
    } bigOval;
    bigOval.height = 5;
    bigOval.width = 7;

Note here that we still need to populate the variables. Further structs from the same template can be created as shown above.

Typedef-ing a struct

If we don’t want to create new struct instances with “struct cube myCube”, we can write a type definition for a struct.

typedef struct cube MegaCube;

I’ve typedef’d previous cube structure as MegaCube. Of course we can choose any name we like here, something descriptive is always a good idea. Again, our friends at Apple to this quite frequently. Now we can create new instances simply by referring to them without the struct word and only use our own definition:

MegaCube rubiksCube;
rubiksCube.length = rubiksCube.height = rubiksCube.width = 3;

This makes our code more readable and is a way of making C code “our own”.

Leave a Reply