< Previous | Contents | Next >

Declaring Pointers

With the first statement in main() I declare a pointer named pAPointer.

int* pAPointer; //declare a pointer

Because pointers work in such a unique way, programmers often prefix pointer variable names with the letter β€œp” to remind them that the variable is indeed a pointer.

Just like an iterator, a pointer is declared to point to a specific type of value. pAPointer is a pointer to int, which means that it can only point to an int value. pAPointer can’t point to a float or a char, for example. Another way to say this is that pAPointer can only store the address of an int.

To declare a pointer of your own, begin with the type of object to which the pointer will point, followed by an asterisk, followed by the pointer name. When you declare a pointer, you can put whitespace on either side of the asterisk. So int* pAPointer;, int *pAPointer;, and int * pAPointer; all declare a pointer named pAPointer.


Tra p

image

When you declare a pointer, the asterisk only applies to the single variable name that immediately follows it. So the following statement declares pScore as a pointer to int and score as an int.

int* pScore, score;

score is not a pointer! It’s a variable of type int. One way to make this clearer is to play with the whitespace and rewrite the statement as:

int *pScore, score;

Understanding Pointer Basics 227


However, the clearest way to declare a pointer is to declare it in its own statement, as in the following lines.

int* pScore; int score;

image