|
|
|
|
|
|
|
LISTING 9.2 MANIPULATING DATA BY USING POINTERS |
|
|
|
 |
|
|
|
|
1: // Listing 9.2 Using pointers
2:
3: #include <iostream.h>
4:
5: int main()
6: {
7: int myAge; // a variable
8: int * pAge = 0; // a pointer
9: myAge = 5;
10: cout << myAge: << myAge << \n;
11:
12: pAge = &myAge; // assign address of myAge to pAge
13:
14: cout << *pAge: << *pAge << \n\n;
15:
16: cout << *pAge = 7\n;
17:
18: *pAge = 7; // sets myAge to 7
19:
20: cout << *pAge: << *pAge << \n;
21: cout << myAge: << myAge << \n\n;
22:
23:
24: cout << myAge = 9\n;
25:
26: myAge = 9;
27:
28: cout << myAge: << myAge << \n;
29: cout << *pAge: << *pAge << \n;
30:
31: return 0;
32: } |
|
|
|
|
|
|
|
|
myAge: 5
*pAge: 5
*pAge = 7
*pAge: 7
myAge: 7
myAge =9
myAge: 9
*pAge: 9 |
|
|
|
|
|
|
|
|
Analysis: This program declares two variables: an int, myAge; and a pointer pAge, which is a pointer to int and which holds the address of myAge. myAge is assigned the value 5 in line 9; this is verified by the printout in line 10. |
|
|
|
|
|