< Previous | Contents | Next >
Because pointers store addresses of objects, you need a way to get addresses into the pointers. One way to do that is to get the memory address of an existing variable and assign it to a pointer. That’s what I do in the following line, which gets the address of the variable score and assigns it to pScore.
pScore = &score; //assign pointer address of variable score
I get the address of score by preceding the variable name with &, the address of operator. (Yes, you’ve seen the & symbol before, when it was used as the reference operator. However, in this context, the & symbol gets the address of an object.)
As a result of the preceding line of code, pScore contains the address of score. It’s as if pScore knows exactly where score is located in the computer’s memory. This means you can use pScore to get to score and manipulate the value stored in score. Figure 7.2 serves as a visual illustration of the relationship between pScore and score.
228 Chapter 7 n Pointers: Tic-Tac-Toe 2.0
Figure 7.2
The pointer pScore points to score, which stores the value 1000.
To prove that pScore contains the address of score, I display the address of the variable and the value of the pointer with the following lines.
cout << "&score is: " << &score << "\n"; //address of score variable cout << "pScore is: " << pScore << "\n"; //address stored in pointer
pScore contains 0x22ff5c, which is the address of score. (The specific addresses displayed by the Pointing program might be different on your system. The important thing is that the values for pScore and &score are the same.)