Programming Tutorials

Manipulating Data by Using Pointers

By: Fazal in C++ Tutorials on 2007-09-14  

Once a pointer is assigned the address of a variable, you can use that pointer to access the data in that variable. Program below demonstrates how the address of a local variable is assigned to a pointer and how the pointer manipulates the values in that variable.

Manipulating data by using pointers.

1:     // Listing 8.2 Using pointers
2:
3:     #include <iostream.h>
4:
5:     typedef unsigned short int USHORT;
6:     int main()
7:     {
8:        USHORT myAge;         // a variable
9:        USHORT * pAge = 0;    // a pointer
10:       myAge = 5;
11:       cout << "myAge: " << myAge << "\n";
12:
13:       pAge = &myAge;     // assign address of myAge to pAge
14:
15:       cout << "*pAge: " << *pAge << "\n\n";
16:
17:       cout << "*pAge = 7\n";
18:
19:       *pAge = 7;         // sets myAge to 7
20:
21:       cout << "*pAge: " << *pAge << "\n";
22:       cout << "myAge: " << myAge << "\n\n";
23:
24:
25:       cout << "myAge = 9\n";
26:
27:       myAge = 9;
28:
29:       cout << "myAge: " << myAge << "\n";
30:       cout << "*pAge: " << *pAge << "\n";
31:
32:    return 0;
33: }

Output: myAge: 5
*pAge: 5

*pAge = 7
*pAge: 7
myAge: 7

myAge = 9
myAge: 9
*pAge: 9

Analysis: This program declares two variables: an unsigned short, myAge, and a pointer to an unsigned short, pAge. myAge is assigned the value 5 on line 10; this is verified by the printout in line 11.
On line 13, pAge is assigned the address of myAge. On line 15, pAge is dereferenced and printed, showing that the value at the address that pAge stores is the 5 stored in myAge. In line 17, the value 7 is assigned to the variable at the address stored in pAge. This sets myAge to 7, and the printouts in lines 21-22 confirm this.

In line 27, the value 9 is assigned to the variable myAge. This value is obtained directly in line 29 and indirectly (by dereferencing pAge) in line 30.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in C++ )

Latest Articles (in C++)