Skip to the workspace
Pebellslearn by building
Pointers and References  ›  Lesson

Raw Pointers

Raw Pointers 12 minA pointer is a variable that stores the memory address of another object, which you follow with the dereference operator to read or change that object.

cpp / Raw Pointers

Explore each scene at your own pace.

01 · The rule

The rule

Raw Pointers

A pointer is a variable that stores the memory address of another object, which you follow with the dereference operator to read or change that object.

Trace addresses and dereferencing while checking whether the pointed-to object still exists.

Rocket Run's collision code needs to change the health of whichever player the asteroid hit. It should not get a copy of that player; it needs a way to reach the real one. The oldest tool C++ has for that is the pointer: a variable that holds an address.

The rule

A pointer stores an address; * follows it, & takes it.

Every object lives somewhere in memory, and that place has an address.

int score = 10;
int* p = &score;   // & takes the address of score
*p = 25;           // * follows the address: score is now 25
  • int* p declares p as a pointer to int.
  • &score gives the address of score.
  • *p means "the object that p points at".

For objects with members, -> follows the pointer and picks a member in one step:

struct Player { int health = 100; };
Player hero;
Player* target = &hero;
target->health -= 30;   // same as (*target).health -= 30

A pointer that points at nothing should hold nullptr. Following a null pointer is undefined behaviour and usually crashes, so check before you use one:

if (target != nullptr) {   // or simply: if (target)
    target->health -= 30;
}

Pointers called raw are these plain T* ones. They only point; they do not own or clean up anything. Later you will meet smart pointers that do.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.