< Previous | Contents | Next >
Unlike references, pointers can point to different objects at different times during the life of a program. Reassigning a pointer works like reassigning any other variable. Next, I reassign pScore with the following line.
pScore = &newScore;
As the result, pScore now points to newScore. To prove this, I display the address of newScore by sending &newScore to cout, followed by the address stored in pScore. Both statements display the same address. Then I send newScore and
*pScore to cout. Both display 5000 because they both access the same chunk of memory that stores this value.
Tra p
Don’t change the value to which a pointer points when you want to change the pointer itself. For example, if I want to change pScore to point to newScore, then the following line would be a big mistake.
*pScore = newScore;
This code simply changes the value to which pScore currently points; it doesn’t change pScore itself. If newScore is equal to 5000, then the previous code is equivalent to *pScore = 5000; and pScore still points to the same variable it pointed to before the assignment.
230 Chapter 7 n Pointers: Tic-Tac-Toe 2.0