Structures

Location
  1. Courses

    /

  2. Quick C course

    /

  3. Structures

What is a structure?

A structure is a special type of variable that is made up of variables.

Let us say there is a structure named 'Character' that is made up of 2 variables (Called members) of type int, with the name 'health' and 'mana'.

Then, we can define a variable of type 'Character' like that:

Character character;

And we can access the member 'health' of the variable 'character', like such:

character.health = 100;

And mana:

character.mana = 60;

Defining a structure

Here, we define the structure from above:

1
2
3
4
5
struct Character { int health; int mana; };

And now we can use the type 'Character':

Character character;

A variable of structure type is called an object. The variable 'character' is therefore an object.

Note that structures are basically a convenient way to group variables. A variable of type 'Character' is simply 2 variables of type int grouped into a single variable.

Pointer of structure type

Let us define a pointer of type 'Character':

Character *ptr;

And make it point to the object 'character' defined earlier:

ptr = &character;

To access the members of the object 'character' through 'ptr' (A pointer), we must use '->' instead of a dot:

ptr->health += 7;