Skip to main content

Section 18.4 Dereferencing Pointers

So how do we use a pointer? We know that the pointer stores a memory address. But how do we use that address to access the data at that address?
The answer is to dereference the pointer. Dereferencing a pointer means using the memory address to access the data at the address it points to. The dereference operator is the asterisk (*). For example, if p is a pointer to an int, then *p is the int that p points to. If p holds the address of an int variable, then *p gives us access to the memory at that address. A good way to pronounce *p is β€œthe thing p points at”.

Note 18.4.1.

This is another time where C++ reuses the same symbol to mean different things. * can be used to specify that a data type is a pointer. It can also be used to dereference a pointer. Or it can mean multiplication.
  • When a data type is to its left, as in int* or double*, it modifies that type to say β€œpointer to a ....”. (There may or may not be a variable name to the right.)
  • When there is no data type to its left and there is a value that is a pointer to its right, as in *p, it says to dereference p.
  • When used between two numeric values, like x * y, it means multiply.
To see dereferencing in action, try this sample in both ActiveCode and with CodeLens:
Listing 18.4.1.
In that example, we use *p to read the β€œint that p points to”. We can also use it to modify that value. If I have a pointer p and I want to modify the value that it is pointing at, I can do something like *p = 20;. We could pronounce *p = 12; as β€œthe thing that p points at gets assigned 20”. Here is a sample of using a pointer to modify a value it points at:
Listing 18.4.2.

Checkpoint 18.4.1.

In the statement int y = *n; what is the * doing?
  • It gives the memory address of n.
  • It dereferences n to get the value it points at.
  • It declares that n is a pointer.
  • It is doing multiplication.

Checkpoint 18.4.2.

In the statement int* n = m; what is the * doing?
  • It gives the memory address of n.
  • It dereferences n to get the value it points at.
  • It declares that n is a pointer.
  • It is doing multiplication.

Checkpoint 18.4.3.

Print the memory address stored in myPointer.

Checkpoint 18.4.4.

Print the value in the variable myPointer points at.

Checkpoint 18.4.5.

Modify the value of the variable myPointer points at to be 42.
You have attempted of activities on this page.