9.4 — Pointers: a note with an address
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 xint* 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; // 20Pointers 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; // 2Reference vs pointer#
| Reference | Pointer | |
|---|---|---|
| Can be empty? | No | Yes (nullptr) |
| Can switch target? | No | Yes |
| How to use the value | just use its name | put * in front |
Good habit
Prefer references when you can. Use pointers when something might be "nothing", or needs to change what it points to.
Tip: press ← / → to move between lessons, / to search.