Sams Teach Yourself C++ in 21 Days

(singke) #1
This is two bytes (16 bits) whose decimal value is 5.
The pointer variable is at location 106. Its value is
000 0000 0000 0000 0000 0000 0110 0101
This is the binary representation of the value 101 , which is the address of theVariable,
whose value is 5.
The memory layout here is schematic, but it illustrates the idea of how pointers store an
address.

Manipulating Data by Using Pointers ............................................................


In addition to using the indirection operator to see what data is stored at a location
pointed to by a variable, you can also manipulate that data. After the pointer is assigned
the address, you can use that pointer to access the data in the variable being pointed to.
Listing 8.2 pulls together what you have just learned about pointers. In this listing, you
see how the address of a local variable is assigned to a pointer and how the pointer can
be used along with the indirection operator to manipulate the values in that variable.

LISTING8.2 Manipulating Data by Using Pointers
1: // Listing 8.2 Using pointers
2: #include <iostream>
3:
4: typedef unsigned short int USHORT;
5:
6: int main()
7: {
8:
9: using namespace std;
10:
11: USHORT myAge; // a variable
12: USHORT * pAge = 0; // a pointer
13:
14: myAge = 5;
15:
16: cout << “myAge: “ << myAge << endl;
17: pAge = &myAge; // assign address of myAge to pAge
18: cout << “*pAge: “ << *pAge << endl << endl;
19:
20: cout << “Setting *pAge = 7... “ << endl;
21: *pAge = 7; // sets myAge to 7
22:
23: cout << “*pAge: “ << *pAge << endl;
24: cout << “myAge: “ << myAge << endl << endl;
25:

228 Day 8

Free download pdf