< Previous | Contents | Next >

Dereferencing Pointers

Just as you dereference an iterator to access the object to which it refers, you dereference a pointer to access the object to which it points. You accomplish the dereferencing the same waywith *, the dereference operator. I put the dereference operator to work with the following line, which displays 1000 because *pScore accesses the value stored in score.

cout << "*pScore is: " << *pScore << "\n\n"; //value pointed to by pointer

Remember, *pScore means, the object to which pScore points.


Tra p

image

Don’t dereference a null pointer because it could lead to disastrous results.

image


Next, I add 500 to score with the following line.

score += 500;

When I send score to cout, 1500 is displayed, as youd expect. When I send

*pScore to cout, the displayed once more.

contents of

score

are

again

sent

to cout, and 1500 is

Understanding Pointer Basics 229


Next, I add 500 to the value to which pScore points with the following line.

*pScore += 500;

Because pScore points to score, the preceding line of code adds 500 to score. Therefore, when I next send score to cout, 2000 is displayed. Then, when I send

*pScore to cout.. .you guessed it, 2000 is displayed again.


Tra p

image

Don’t change the value of a pointer when you want to change the value of the object to which the pointer points. For example, if I want to add 500 to the int that pScore points to, then the following line would be a big mistake.

pScore += 500;

The preceding code adds 500 to the address stored in pScore, not to the value to which pScore originally pointed. As a result, pScore now points to some address that might contain anything. Dereferencing a pointer like this can lead to disastrous results.

image