Programming in C

(Barry) #1

244 Chapter 11 Pointers


printf ("i1 = %i, *pointers.p1 = %i\n", i1, *pointers.p1);
printf ("i2 = %i, *pointers.p2 = %i\n", i2, *pointers.p2);
return 0;
}

Program 11.5 Output
i1 = 100, *pointers.p1 = 100
i2 = -97, *pointers.p2 = -97

After the variables have been defined, the assignment statement
pointers.p1 = &i1;
sets the p1member of pointerspointing to the integer variable i1, whereas the next
statement
pointers.p2 = &i2;
sets the p2member pointing to i2. Next,–97is assigned to the variable that is pointed
to by pointers.p2. Because you just set this to point to i2,–97is stored in i2.No
parentheses are needed in this assignment statement because, as mentioned previously, the
structure member operator .has higher precedence than the indirection operator.
Therefore, the pointer is correctly referenced from the structure beforethe indirection
operator is applied. Of course, parentheses could have been used just to play it safe, as at
times it can be difficult to try to remember which of two operators has higher prece-
dence.
The two printfcalls that follow each other in the preceding program verify that the
correct assignments were made.
Figure 11.3 has been provided to help you understand the relationship between the
variables i1,i2,and pointersafter the assignment statements from Program 11.5 have
been executed. As you can see in Figure 11.3, the p1member points to the variable i1,
which contains the value 100 , whereas the p2member points to the variable i2, which
contains the value –97.

Linked Lists


The concepts of pointers to structures and structures containing pointers are very pow-
erful ones in C, for they enable you to create sophisticated data structures, such as linked
lists,doubly linked lists,and trees.
Suppose you define a structure as follows:
struct entry
{
int value;
struct entry *next;
};

Program 11.5 Continued
Free download pdf