Programming in C

(Barry) #1

252 Chapter 11 Pointers


Program 11.7 Output
100
200
300

The program defines the variables n1,n2,and n3and the pointer variable list_pointer,
which is initially set to point to n1, the first entry in the list.The next program state-
ments link together the three elements of the list, with the next member of n3set to the
null pointer to mark the end of the list.
A whileloop is then set up to sequence through each element of the list.This loop is
executed as long as the value of list_pointeris not equal to the null pointer.The
printfcall inside the whileloop displays the valuemember of the entry currently
pointed to by list_pointer.
The statement that follows the printfcall,
list_pointer = list_pointer->next;
has the effect of taking the pointer from the nextmember of the structure pointed to by
list_pointerand assigning it to list_pointer.So, the first time through the loop, this
statement takes the pointer contained in n1.next(remember,list_pointerwas initially
set pointing to n1) and assigns it to list_pointer.Because this value is not null—it’s a
pointer to the entrystructure n2—the whileloop is repeated.
The second time through, the whileloop results in the display of n2.value, which is
200 .The nextmember of n2is then copied into list_pointer, and because you set this
value to point to n3,list_pointerpoints to n3by the end of the second pass through
the loop.
When the whileloop is executed the third time, the printfcall displays the value of
300 as contained in n3.value. At that point,list_pointer->next(which is actually
n3.next) is copied into list_pointer, and, because you set this member to the null
pointer, the whileloop terminates after it has been executed three times.
Trace through the operation of the whileloop just discussed, using a pencil and
paper, if necessary, to keep track of the values of the various variables. Understanding the
operation of this loop is the key to your understanding the operation of pointers in C.
Incidentally, it should be noted that this same whileloop can be used to sequence
through the elements of a list of anysize, provided the end of the list is marked by the
null pointer.
When working with actual linked lists in a program, you will not normally link
together list entries that have been explicitly defined like in the program examples in
this section.You did that here just to illustrate the mechanics of working with a linked
list. In actual practice, you will typically ask the system to give you memory for each
new list entry and you will link it into the list while the program is executing.This is
done with a mechanism known as dynamic memory allocation, and is covered in
Chapter 17.
Free download pdf