Programming in C

(Barry) #1
Working with Pointers and Structures 247

n1.value = 100;
n2.value = 200;
n3.value = 300;

n1.next = &n2;
n2.next = &n3;

i = n1.next->value;
printf ("%i ", i);

printf ("%i\n", n2.next->value);

return 0;
}


Program 11.6 Output


200 300


The structures n1,n2,and n3are defined to be of type struct entry, which consists of
an integer member called valueand a pointer to an entrystructure called next.The
program then assigns the values 100 , 200 ,and 300 to the value members of n1,n2, and
n3,respectively.
The next two statements in the program


n1.next = &n2;
n2.next = &n3;


set up the linked list, with the nextmember of n1pointing to n2and the nextmember
of n2pointing to n3.
Execution of the statement


i = n1.next->value;


proceeds as follows:The valuemember of the entrystructure pointed to by n1.nextis
accessed and assigned to the integer variable i. Because you set n1.nextto point to n2,
the valuemember of n2is accessed by this statement.Therefore, this statement has the
net result of assigning 200 to i, as verified by the printfcall that follows in the pro-
gram.You might want to verify that the expression n1.next->valueis the correct one
to use and not n1.next.value, because the n1.nextfield contains a pointer to a struc-
ture, and not the structure itself.This distinction is important and can quickly lead to
programming errors if it is not fully understood.
The structure member operator .and the structure pointer operator ->have the
same precedence in the C language. In expressions such as the preceding one, where


Program 11.6 Continued
Free download pdf