Declaring a Pointer in C++
A char variable in C++ is designed to hold an ASCII character, an int an integer number, and a double a floating-point number. Similarly, a pointer variable is designed to hold a memory address. You declare a pointer variable by adding an asterisk (*) to the end of the type of the object that the pointer points at, as in the following example:
char* pChar; // pointer to a character int* pInt; // pointer to an int
A pointer variable that has not otherwise been initialized contains an unknown value. Using the ampersand (&) operator, you can initialize a pointer variable with the address of a variable of the same type:
char cSomeChar = 'a'; char* pChar; pChar = &cSomeChar;
In this snippet, the variable cSomeChar has some address. For argument’s sake, say that C++ assigned it the address 0x1000. (C++ also initialized that location with the character ‘a’.) The variable pChar also has a location of its own, perhaps 0x1004. The value of the expression &cSomeChar is 0x1000, and its type is char* (read “pointer to char”).
So the assignment on the third line of the snippet example stores the value 0x1000 in the variable pChar.
Take a minute to really understand the relationship between the figure and the three lines of C++ code in the snippet. The first declaration says, “go out and find a 1-byte location in memory, assign it the name cSomeChar, and initialize it to ‘a’.” In this example, C++ picked the location 0x1000.
The next line says, “go out and find a location large enough to hold the address of a char variable and assign it the name pChar.” In this example, C++ assigned pChar to the location 0x1004.
The third line says, “assign the address of cSomeChar (0x1000) to the variable pChar.” The figure represents the state of the program after these three statements.
“So what?” you say. Here comes the really cool part, as demonstrated in the following expression:
*pChar = 'b';
This line says, “store a ‘b’ at the char location pointed at by pChar.” This is demonstrated in the following figure. To execute this expression, C++ first retrieves the value stored in pChar (that would be 0x1000). It then stores the character ‘b’ at that location.
The * when used as a binary operator means “multiply”; when used as a unary operator, * means “find the thing pointed at by.” Similarly & has a meaning as a binary operator, but as a unary operator, it means “take the address of.”
So what’s so exciting about that? After all, you could achieve the same effect by simply assigning a ‘b’ to cSomeChar directly:
cSomeChar = 'b';
Why go through the intermediate step of retrieving its address in memory? Because there are several problems that can be solved only with pointers.