Skip to main content Skip to navigation

2.9 Structures

A structure in C allows the user to create an object that can collect together objects of differing type and size. An example of a structure is a database entry. Consider a database for tennis players, where the entries are name (character array type), age (integer type), prizemoney (real type), number of titles (integer type). To make use of this database as a structure (called tennis) in a C program, it first must be defined:

struct tennis {
  char name[100];
  int age;
  float prize;
  int titles;
};

This definition should come at the top of the program, with all the other declarations. You can now use this stucture definition as you would any type definition. Therefore, you can use this "user-declared" type to declare variables. The only difference between declaring a variable based on normal types and declaring a variable based on a structure, is that in the latter case you must prefix your declaration with the word struct. Following the above example, we could define a variable player in the following way:

struct tennis player;

This would allow us to assign the details of one tennis player. Assignment of values for the various components of the variable player can be done in the following way:

strcpy(player.name, "Roger Federer");
player.age=35;
player.prize=5000000.99;
player.titles=65;

This format of variable_name.structure_component can be used in general to access any components of a variable based on a structure, e.g., for arithmetic or comparitive operations.

When passing structures to functions it is typical to pass a pointer to the structure. To access an entry name with such a pointer ptr, one should use (*ptr).name. This occurs so often that a short-hand has been introduced: the arrow symbol, ->. Then accessing name is established by ptr->name. Continuing on from the above example:

struct tennis *ptr;       // Create a pointer to a variable of type tennis
 ....
ptr = &player;            // Make ptr point to player
age_player = ptr->age;