Sams Teach Yourself C++ in 21 Days

(singke) #1
Understanding Pointers 225

8


For a pointer to hold an address, the address must be assigned to it. For the previous
example, you must specifically assign the address of howOldto pAge, as shown in the fol-
lowing example:
unsigned short int howOld = 50; // make a variable
unsigned short int * pAge = 0; // make a pointer
pAge = &howOld; // put howOld’s address in pAge
The first line creates a variable named howOld—whose type is unsigned short int—
and initializes it with the value 50. The second line declares pAgeto be a pointer to type
unsigned short intand initializes it to zero. You know that pAgeis a pointer because
of the asterisk (*) after the variable type and before the variable name.
The third and final line assigns the address of howOldto the pointer pAge. You can tell
that the address of howOldis being assigned because of the address-of operator (&). If the
address-of operator had not been used, the value of howOldwould have been assigned.
That might, or might not, have been a valid address.
At this point,pAgehas as its value the address of howOld. howOld, in turn, has the value
50. You could have accomplished this with one fewer step, as in
unsigned short int howOld = 50; // make a variable
unsigned short int * pAge = &howOld; // make pointer to howOld
pAgeis a pointer that now contains the address of the howOldvariable.

Getting the Value from a Variable ..................................................................


Using pAge, you can actually determine the value of howOld, which in this case is 50.
Accessing the value stored in a variable by using a pointer is called indirection because
you are indirectly accessing the variable by means of the pointer. For example, you can
use indirection with the pAgepointer to access the value in howOld.
Indirection means accessing the value at the address held by a pointer. The pointer pro-
vides an indirect way to get the value held at that address.

NOTE Practice safe computing: Initialize all of your pointers!


With a normal variable, the type tells the compiler how much memory is
needed to hold the value. With a pointer, the type does not do this; all
pointers are the same size—usually four bytes on a machine with a 32-bit
processor and eight bytes on a machine with a 64-bit processor.

NOTE

Free download pdf