9.4 — Pointers: a note with an address

📘 Chapter 9⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

What is a pointer?#

A pointer is a variable that holds an address. It's like a note that says where a box is.

C++
int x { 5 };int* ptr { &x };   // ptr holds the address of x

int* reads as "pointer to int".

Following the pointer#

Put * in front of a pointer to reach the box it points at. This is called dereferencing.

C++
std::cout << *ptr;   // 5 — the value at that address *ptr = 20;           // change the box ptr points tostd::cout << x;      // 20

Pointers can move#

Unlike a reference, a pointer can point to a different box later:

C++
int a { 1 };int b { 2 };int* p { &a };p = &b;          // now points to bstd::cout << *p; // 2

Reference vs pointer#

ReferencePointer
Can be empty?NoYes (nullptr)
Can switch target?NoYes
How to use the valuejust use its nameput * in front
Good habit

Prefer references when you can. Use pointers when something might be "nothing", or needs to change what it points to.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.