C++ Pointers, Explained Like a Treasure Map
A pointer is just an address. A beginner-friendly mental model for references, dereferencing, and memory.
Pointers scare beginners, but the concept is simple: a pointer is just a number that tells the computer where something lives in memory.
The address bar of memory
Every variable has an address, like a house number on a street.
int score = 42;
std::cout << &score; // 0x7ffee2c3d8a4 — the "address" of score
&score gives you the address. A pointer stores that address:
int* ptr = &score; // ptr points to score
std::cout << *ptr; // 42 — dereference: read the house
*ptr = 100; // write through the pointer
std::cout << score; // 100 — score changed!
Why bother?
- Avoid copying large data — pass a pointer instead of copying a whole array.
- Share one value across functions.
- Build dynamic structures — linked lists and trees are trees of pointers.
Pointers and arrays are siblings
int nums[] = {10, 20, 30};
int* p = nums; // decay: array becomes pointer to first element
std::cout << *(p + 1); // 20 — pointer arithmetic
The two great enemies
Null pointers — a pointer pointing nowhere. Always check before dereferencing:
if (ptr != nullptr) { /* safe */ }
Dangling pointers — pointing at memory that was freed. Prefer smart pointers in modern C++:
auto p = std::make_unique<int>(42); // auto-cleaned, no delete needed
The mental model
| If pointers are | then |
|---|---|
| street addresses | * is "open the door" |
& is "ask for the address" | referencing |
nullptr is "this address is empty" | sentinel |
Practice
Write a function that swaps two numbers using pointers. Then rewrite it with references (int&) and compare readability. You will use both forever.
Pointers are not the enemy — they are just the computer opening its doors for you.