|
|
|
|
|
|
|
In line 12, pAge is assigned the address of myAge. In line 14, pAge is dereferenced and printed, showing that the value at the address that pAge stores is the 5 stored in myAge. In line 18, the value 7 is assigned to the variable at the address stored in pAge. This sets myAge to 7, and the printouts in lines 20 and 21 confirm this. |
|
|
|
|
|
|
|
|
In line 26, the value 9 is assigned to the variable myAge. This value is obtained directly in line 28 and indirectlyby dereferencing pAgein line 29. |
|
|
|
|
|
|
|
|
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 make sure? Listing 9.3 illustrates this idea. |
|
|
|
|
|
|
|
|
LISTING 9.3 FINDING OUT WHAT IS STORED IN POINTERS |
|
|
|
 |
|
|
|
|
1: // Listing 9.3 What is stored in a pointer.
2:
3: #include <iostream.h>
4:
5: int main()
6: {
7: unsigned short int myAge = 5, yourAge = 10;
8: unsigned short int * pAge = &myAge; // a pointer
9:
10: cout << myAge:\t << myAge << \tyourAge:\t << yourAge << \n;
11: cout << &myAge:\t << &myAge << \t&yourAge:\t << &yourAge <<\n;
12:
13: cout << pAge:\t << pAge << \n;
14: cout << *pAge:\t << *pAge << \n;
15:
16: pAge = &yourAge; // reassign the pointer
17:
18: cout << myAge:\t << myAge << \tyourAge:\t << yourAge << \n;
19: cout << &myAge:\t << &myAge << \t&yourAge:\t << &yourAge <<\n;
20:
21: cout << pAge:\t << pAge << \n;
22: cout << *pAge:\t << *pAge << \n;
23:
24: cout << &pAge:\t << &pAge << \n;
25: return 0;
26: } |
|
|
|
|
|