Node:Pointers to structures, Next:, Previous:Nested structures, Up:struct



Pointers to structures

Although a structure cannot contain an instance of its own type, it can can contain a pointer to another structure of its own type, or even to itself. This is because a pointer to a structure is not itself a structure, but merely a variable that holds the address of a structure. Pointers to structures are quite invaluable, in fact, for building data structures such as linked lists and trees. (See Complex data structures.)

A pointer to a structure type variable is declared by a statement such as the following:

struct personal_data *my_struct_ptr;

The variable my_struct_ptr is a pointer to a variable of type struct personal_data. This pointer can be assigned to any other pointer of the same type, and can be used to access the members of its structure. According to the rules we have outlined so far, this would have to be done like so:

struct personal_data person1;

my_struct_ptr = &person1;
(*my_struct_ptr).day_of_birth = 23;

This code example says, in effect, "Let the member day_of_birth of the structure pointed to by my_struct_ptr take the value 23." Notice the use of parentheses to avoid confusion about the precedence of the * and . operators.

There is a better way to write the above code, however, using a new operator: ->. This is an arrow made out of a minus sign and a greater than symbol, and it is used as follows:

my_struct_ptr->day_of_birth = 23;

The -> enables you to access the members of a structure directly via its pointer. This statement means the same as the last line of the previous code example, but is considerably clearer. The -> operator will come in very handy when manipulating complex data structures. (See Complex data structures.)