< previous page page_142 next page >

Page 142
Output:
myAge:    5            yourAge:  10
&myAge:   0x355C       &yourAge: 0x355E
pAge:     0x355C
*pAge:    5
myAge:    5           yourAge:  10
&myAge:   0x355C      &yourAge: 0x355E
pAge:     0x355E
*pAge:    10
&pAge:    0
(Your output may look different.)
Analysis: In line 7, myAge and yourAge are declared to be variables of type unsignedshort integer. In line 8, pAge is declared to be a pointer to an unsigned short integer, and it is initialized with the address of the variable myAge.
Lines 10 and 11 print the values and the addresses of myAge and yourAge. Line 13 prints the contents of pAge, which is the address of myAge. Line 14 prints the result of dereferencing pAge, which prints the value at pAgethe value in myAge, or 5.
This is the essence of pointers. Line 13 shows that pAge stores the address of myAge, and line 14 shows how to get the value stored in myAge by dereferencing the pointer pAge. Make sure that you understand this fully before you go on. Study the code and look at the output.
In line 16, pAge is reassigned to point to the address of yourAge. The values and addresses are printed again. The output shows that pAge now has the address of the variable yourAge, and that dereferencing obtains the value in yourAge.
Line 24 prints the address of pAge itself. Like any variable, it too has an address, and that address can be stored in a pointer. (Assigning the address of a pointer to another pointer will be discussed shortly.)
DO
DO use the indirection operator (*) to access the data stored at the address in a pointer.
DO initialize all pointers either to a valid address or to null (0).
DO remember the difference between the address in a pointer and the value at that address.

 
< previous page page_142 next page >

If you like this book, buy it!