Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Pointers 231

8


myAge: 5 yourAge: 10
&myAge: 0012FF7C &yourAge: 0012FF78
pAge: 0012FF78
*pAge: 10

&pAge: 0012FF74
(Your output might look different.)
On line 9,myAgeand yourAgeare declared to be variables of type unsigned
shortinteger. On line 12,pAgeis declared to be a pointer to an unsigned short
integer, and it is initialized with the address of the variable myAge.
Lines 14–18 print the values and the addresses of myAgeand yourAge. Line 20 prints the
contentsof pAge, which is the address of myAge. You should notice that the output con-
firms that the value of pAgematches the value of myAge’s address. Line 21 prints the
result of dereferencing pAge, which prints the value at pAge—the value in myAge, or 5.
This is the essence of pointers. Line 20 shows that pAgestores the address of myAge, and
line 21 shows how to get the value stored in myAgeby dereferencing the pointer pAge. Be
certain that you understand this fully before you go on. Study the code and look at the
output.
On line 25,pAgeis reassigned to point to the address of yourAge. The values and
addresses are printed again. The output shows that pAgenow has the address of the vari-
able yourAgeand that dereferencing obtains the value in yourAge.
Line 36 prints the address of pAgeitself. Like any variable, it 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.)

ANALYSIS


DOuse the indirection operator (*) to
access the data stored at the address in a
pointer.
DOinitialize all pointers either to a valid
address or to null ( 0 ).

DON’Tconfuse the address in a pointer
with the value at that address.

DO DON’T


Using Pointers
To declare a pointer, write the type of the variable or object whose address will be stored
in the pointer, followed by the pointer operator (*) and the name of the pointer. For
example,
Free download pdf