How to Use Pointer Variables in C++ - dummies

How to Use Pointer Variables in C++

By Stephen R. Davis

A pointer variable is a variable that contains an address, usually the address of another variable. This is somewhat analogous to a hotel. When you make your reservation, you may be assigned room 0x100. You might tell your son that you will be in room 0x100 on your trip. Your son can act as a pointer variable of sorts. Anyone can ask him at any time, “Where’s your father staying?”

By the way, notice something about pointer variables: No matter where your son is, and no matter how many other people he tells of your whereabouts, you’re still in room 0x100.

The following pseudo-C++ demonstrates how the two address operators shown in this table are used.

Pointer Operators
Operator Meaning
& (unary) (In an expression) the address of
& (unary) (In a declaration) reference to
* (unary) (In an expression) the thing pointed at by
* (unary) (In a declaration) pointer to
mySon = &DadsRoom; // tell mySon the address of Dad's Room
room = *mySon;     // "Dad's room number is"

The following C++ code snippet shows these operators used correctly:

void fn()
   int  nVar;
   int* pnVar;
   pnVar  = &nVar;   // pnVar now points to nVar
   *pnVar = 10;      // stores 10 into the int location
}                    // pointed at by pnVar

The function fn() begins with the declaration of nVar. The next statement declares the variable pnVar to be a variable of type pointer to an int.

Pointer variables are declared like normal variables except for the addition of the unary * character. This * character can appear anywhere between the base type name — the following two declarations are equivalent:

int* pnVar1;
int *pnVar2;

Which you use is a matter of personal preference.

The * character is called the asterisk character (that’s logical enough), but because asterisk is hard to say, many programmers have come to call it the star or, less commonly, the splat character. Thus, they would say “star pnVar” or “splat pnVar.”

In an expression, the unary operator & means “the address of.” Thus, you would read the assignment pnVar = &nVar; as “pnVar gets the address of nVar.”