C++

What is a pointer ?

New Term: A pointer is a variable that holds a memory address.

To understand pointers, you must know a little about computer memory. Computer memory is divided into sequentially numbered memory locations. Each variable is located at a unique location in memory, known as its address.

Different computers number this memory using different, complex schemes. Usually programmers don’t need to know the particular address of any given variable, because the compiler handles the details. If you want this information, though, you can use the address of operator (&), which is illustrated in Listing 8.1.

Listing 8.1. Demonstrating address of variables.

1: // Listing 8.1 Demonstrates address of operator

2: // and addresses of local variables

3:

4: #include <iostream.h>

5:

6: int main()

7: {

8: unsigned short shortVar=5;

9: unsigned long longVar=65535;

10: long sVar = -65535;

11:

12: cout << "shortVar:\t" << shortVar;

13: cout << " Address of shortVar:\t";

14: cout << &shortVar _<< "\n";

15:

16: cout << "longVar:\t" << longVar;

17: cout << " Address of longVar:\t" ;

18: cout << &longVar _<< "\n";

19:

20: cout << "sVar:\t" << sVar;

21: cout << " Address of sVar:\t" ;

22: cout << &sVar _<< "\n";

23:

24: return 0;

25: }

Output:

shortVar: 5 Address of shortVar: 0x8fc9:fff4

longVar: 65535 Address of longVar: 0x8fc9:fff2

sVar: -65535 Address of sVar: 0x8fc9:ffee

(Your printout may look different.)

ANALYSIS: Three variables are declared and initialized: a short in line 8, an unsigned long in line 9, and a long in line 10. Their values and addresses are printed in lines 12-16, by using the address of operator (&). The value of shortVar is 5, as expected, and its address is 0x8fc9:fff4 when run on my 80386-based computer. This complicated address is computer-specific and may change slightly each time the program is run. Your results will be different. What doesn’t change, however, is that the difference in the first two addresses is two bytes if your computer uses two-byte short integers. The difference between the second and third is four bytes if your computer uses four-byte long integers. Figure 8.2 illustrates how the variables in this program would be stored in memory.

8.2.JPG (20211 bytes)
Figure 8.2. Illustration of variable storage.

There is no reason why you need to know the actual numeric value of the address of each variable. What you care about is that each one has an address and that the right amount of memory is set aside. You tell the compiler how much memory to allow for your variables by declaring the variable type; the compiler automatically assigns an address for it. For example, a long integer is typically four bytes, meaning that the variable has an address to four bytes of memory.

Back to Index