Lesson 117 +10 XP

Dereferencing Pointers

Dereferencing Pointers

A pointer stores where something lives. Dereferencing makes the what: applying the * operator to a pointer gives the value at that address.

Read through the pointer

#include <iostream>
using namespace std;

string food = "Pizza";
string* ptr = &food;

cout << ptr << endl;    // the address, e.g. 0x7ffe0000a1c
cout << *ptr << endl;   // Pizza  (the dereference)

*ptr travels to the address the pointer holds and brings back the value stored there.

Declaration vs dereference

The star does two jobs; the position tells them apart:

  • string ptr; - the is next to the type, so it marks a pointer.
  • ptr; - the is next to the name in an expression, so it dereferences.
string* ptr = &food;  // declaration: the * marks the pointer
cout << *ptr;         // expression:  the * fetches the value

Write through the pointer

*ptr = "Sushi";
cout << food << endl;   // Sushi

Assigning to *ptr writes a new value at the address - which changes food.

A reference needs no star

string& ref = food;   // an alias; behaves like the string itself
cout << *ptr;         // dereference, the star is required
cout << ref;          // reference, no star needed

Both reach the same string, but only the pointer needs dereferencing.

TL;DR

  • *ptr dereferences: it produces the value at the stored address.
  • in a declaration marks a pointer; in an expression dereferences.
  • *ptr = value writes through the pointer.
  • A reference reads the value directly.