Understanding Pointers 229
26: cout << “Setting myAge = 9... “ << endl;^8
27: myAge = 9;
28:
29: cout << “myAge: “ << myAge << endl;
30: cout << “*pAge: “ << *pAge << endl;
31:
32: return 0;
33: }
myAge: 5
*pAge: 5
Setting *pAge = 7...
*pAge: 7
myAge: 7
Setting myAge = 9...
myAge: 9
*pAge: 9
This program declares two variables: an unsigned short,myAge, and a pointer
to an unsigned short,pAge. myAgeis assigned the value 5 on line 14; this is ver-
ified by the printout on line 16.
On line 17,pAgeis assigned the address of myAge. On line 18,pAgeis dereferenced—
using the indirection operator (*)—and printed, showing that the value at the address that
pAgestores is the 5 stored in myAge.
On line 21, the value 7 is assigned to the variable at the address stored in pAge. This sets
myAgeto 7 , and the printouts on lines 23 and 24 confirm this. Again, you should notice
that the indirect access to the variable was obtained by using an asterisk—the indirection
operator in this context.
On line 27, the value 9 is assigned to the variable myAge. This value is obtained directly
on line 29 and indirectly (by dereferencing pAge) on line 30.
Examining the Address ..................................................................................
Pointers enable you to manipulate addresses without ever knowing their real value. After
today, you’ll take it on faith that when you assign the address of a variable to a pointer, it
really has the address of that variable as its value. But just this once, why not check to be
certain? Listing 8.3 illustrates this idea.
OUTPUT
LISTING8.2 continued
ANALYSIS