Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

Raw Pointers

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.

The shortcut

Read a declaration from right to left, starting at the name.

Reading const int* pStep 1 of 4
  1. Start at the name

    p is ...

The trap is mixing up the two meanings of each symbol. In a declaration, * means "pointer to". In an expression, *p follows the pointer and &x takes an address.

Drills

Answer fast — trust the rule.

quick drill

After int score = 10; int* p = &score; *p = 25;, what is score?

quick drill

What value does p itself hold after int* p = &score;?

quick drill

Which value should a pointer hold when it points at no object?

quick drill

What does const int* p declare?

quick drill

After int score = 10; int* a = &score; int* b = a; *b = 7;, what is *a?

Remember

  • A pointer stores an address; * follows it, & takes it.
  • Shortcut: read declarations from right to left.
  • Trap: check for nullptr before following a pointer.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainTwo ways to reach the score

In Rocket Run, int score = 10; int* p = &score; *p = 25; runs. Explain what p holds, what *p = 25 does, what score is afterwards, and why a pointer should be checked before it is used.