C Programming Tutorial
Computer Tutorial

Structure Pointers

Structure Pointers

C allows pointers to structures just as it allows pointers to any other type of object. However, there are some special aspects to structure pointers, which are described next.

Declaring a Structure Pointer

Like other pointers, structure pointers are declared by placing * in front of a structure variable's name. For example, assuming the previously defined structure addr, the following declares addr_pointer as a pointer to data of that type:
struct addr *addr_pointer;

Using Structure Pointers

There is one major drawback to passing all but the simplest structures to functions: the overhead needed to push the structure onto the stack when the function call is executed. (Recall that arguments are passed to functions on the stack.) For simple structures with few members, this overhead is not too great. If the structure contains many members, however, or if some of its members are arrays, run-time performance may degrade to unacceptable levels. The solution to this problem is to pass a pointer to the structure.
When a pointer to a structure is passed to a function, only the address of the structure is pushed on the stack. This makes for very fast function calls. A second advantage, in some cases, is that passing a pointer makes it possible for the function to modify the contents of the structure used as the argument.

To find the address of a structure variable, place the & operator before the structure's name.
struct bal
      float balance;
      char name[80];
} person;
struct bal *p; /* declare a structure pointer */
This places the address of the structure person into the pointer p:
p = &person;
To access the members of a structure using a pointer to that structure, you must use the –> operator. For example, this references the balance field:
p –> balance;