|
|
 |
|
|
|
|
unsigned short * pAge = 0; // make a pointer to an unsigned short |
|
|
|
| | When the pointer is dereferenced, the indirection operator indicates that the value at the memory location stored in the pointer is to be accessed, rather than the address itself: |  |
|
|
|
|
*pAge = 5; // assign 5 to the value at pAge |
|
|
|
| | Also note that this same character (*) is used as the multiplication operator. The compiler knows which operator to call based on context. |
|
|
|
|
|
Pointers, Addresses, and Variables |
|
|
|
|
|
|
|
|
It is important to distinguish between a pointer, the address that the pointer holds, and the value at the address held by the pointer. This is the source of much of the confusion about pointers. |
|
|
|
|
|
|
|
|
Consider the following code fragment: |
|
|
|
|
|
|
|
|
int theVariable = 5;
int * pPointer = &theVariable ; |
|
|
|
|
|
|
|
|
theVariable is declared to be an integer variable initialized with the value 5. pPointer is declared to be a pointer to an integer; it is initialized with the address of theVariable. pPointer is the pointer. The address that pPointer holds is the address of theVariable. The value at the address that pPointer holds is 5. Figure 9.3 shows a schematic representation of theVariable and pPointer. |
|
|
|
|
|
|
|
|
FIGURE 9.3
A schematic representation of memory. |
|
|
|
|
|
|
|
|
Manipulating Data by Using Pointers |
|
|
|
|
|
|
|
|
After a pointer is assigned the address of a variable, you can use that pointer to access the data in that variable. Listing 9.2 demonstrates how the address of a local variable is assigned to a pointer and how the pointer manipulates the values in that variable. |
|
|
|
|
|