The Analogy: The House Number
A variable is a house with something inside it. A pointer is a slip of paper with a house number written on it.
The slip is not the house. It is small, it fits in your pocket, and you can copy it a thousand times without building a thousand houses. To see what is inside the house you have to go to the address — that is dereferencing. To find out a house's number in the first place you ask for its address with &.
The analogy carries the dangers too. The slip might be blank (a null pointer). It might carry the number of a house that has been demolished (a dangling pointer). It might carry a number you made up, pointing at somebody else's building. C++ will happily walk you to any address you name and let you rearrange the furniture.
Pointers are how C++ talks about memory directly. Everything else in this module — arrays, references, containers — is built on them.
Syntax or Core Structure
#include <iostream>
#include <string>
int main() {
int score{42};
int* ptr = &score; // & means "address of"
std::cout << ptr << "\n"; // an address, e.g. 0x7ffd4c2a
std::cout << *ptr << "\n"; // 42 -- * means "value at that address"
std::cout << &score << "\n"; // the same address
*ptr = 100; // write THROUGH the pointer
std::cout << score << "\n"; // 100 -- we changed the original
// Null: a pointer that deliberately points at nothing
int* nothing = nullptr;
if (nothing == nullptr) { std::cout << "empty\n"; }
if (!nothing) { std::cout << "also empty\n"; }
// std::cout << *nothing; // CRASH -- never dereference null
// Pointers can be reseated, unlike references
int other{7};
ptr = &other; // now names a different variable
std::cout << *ptr << "\n"; // 7
// const in two positions, meaning two different things
const int* readOnly = &score; // cannot change the VALUE through it
int* const fixedTarget = &score; // cannot change WHERE it points
const int* const both = &score; // neither
// Pointers to structs use ->
struct Point { int x; int y; };
Point p{3, 4};
Point* pp = &p;
std::cout << pp->x << "\n"; // 3 -- shorthand for (*pp).x
return 0;
}
The * does two unrelated jobs, which is the main source of early confusion. In a declaration (int* ptr) it means "this is a pointer". In an expression (*ptr) it means "go and fetch the value".
Technical Depth: Null, Dangling, Arrays and Why You Rarely Need Them
The three states of a pointer
int* a; // 1. UNINITIALISED -- holds garbage. The worst state.
int* b = nullptr; // 2. NULL -- deliberately points at nothing. Checkable.
int x{5};
int* c = &x; // 3. VALID -- points at a live object.
// std::cout << *a; // undefined behaviour: an address you never chose
// std::cout << *b; // crashes reliably -- which is far better
std::cout << *c; // 5
An uninitialised pointer is more dangerous than a null one, because null crashes immediately and predictably while garbage may appear to work for months. Always initialise a pointer, to nullptr if you have nothing for it yet.
Use nullptr, not NULL and not 0. nullptr has its own type, so it cannot be mistaken for an integer in overload resolution — a real bug in older code.
Dangling pointers
int* danglingLocal() {
int local{42};
return &local; // local dies here -- the address is now meaningless
}
int* p = danglingLocal();
std::cout << *p; // undefined behaviour: may print 42, may print junk
// The vector version, which happens in real code
std::vector<int> v{1, 2, 3};
int* first = &v[0];
v.push_back(4); // may move the buffer
*first = 99; // writes to freed memory
A pointer does not keep anything alive. When the target's lifetime ends, the pointer still holds the old number and nothing marks it as stale. Setting it to nullptr after you are done is a cheap habit that turns silent corruption into an obvious crash.
Arrays and pointers are nearly the same thing
int data[5]{10, 20, 30, 40, 50};
int* p = data; // an array name decays to a pointer to its first element
std::cout << *p << "\n"; // 10
std::cout << p[2] << "\n"; // 30 -- [] works on pointers too
std::cout << *(p+2) << "\n"; // 30 -- exactly the same thing
// In fact, data[2] is DEFINED as *(data + 2)
Subscripting is pointer arithmetic in disguise. Adding 2 to an int* advances by two ints, not two bytes — the compiler scales by the element size. That is why the pointer's type matters and why void* cannot be dereferenced.
Pointer parameters versus reference parameters
void byPointer(int* p) {
if (p == nullptr) { return; } // you MUST check
*p *= 2;
}
void byReference(int& r) {
r *= 2; // guaranteed to exist -- no check needed
}
int x{5};
byPointer(&x); // explicit at the call site that something may be modified
byReference(x); // looks like a plain call
byPointer(nullptr); // legal -- "no value" is expressible
Both let a function modify the caller's data. The difference is what they say: a pointer parameter announces that absence is a valid input. If the argument must always exist, use a reference — the compiler then guarantees it and the function body needs no null check.
When to use a raw pointer in modern C++
Almost never for ownership. The modern hierarchy, best first:
- A value or a reference —
std::string,const T&. Use these unless you cannot. std::vector/std::stringfor dynamic collections, instead ofnew[].std::optional<T>(C++17) for "a value that might not be there".std::unique_ptr/std::shared_ptrfor objects with heap lifetimes — these clean up automatically.- A raw non-owning pointer for "look at this thing, which someone else owns, and it might be null".
newanddeleteby hand — essentially never in application code.
// The old way: you must remember to delete, and any early return leaks
int* buffer = new int[100];
delete[] buffer;
// The modern way: freed automatically, exception-safe
std::vector<int> buffer(100);
Raw pointers remain worth understanding because they explain how everything else works, they appear throughout C libraries and older codebases, and unique_ptr and vector are thin, safe wrappers over exactly this machinery. But writing new in new code is a design smell.
Pointer, reference, value
| Value | Reference | Pointer | |
|---|---|---|---|
| Copies the data | yes | no | no |
| Can be null | n/a | no | yes |
| Can be reseated | n/a | no | yes |
Needs * / -> | no | no | yes |
| Can be stored in a container | yes | not directly | yes |
| Arithmetic | no | no | yes |
| Announces "may be absent" | no | no | yes |
Real World Example: A Student Lookup
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
struct Student {
std::string name;
int id{0};
double average{0.0};
};
// Returns a pointer precisely BECAUSE the answer may not exist.
// A reference could not express "not found".
Student* findById(std::vector<Student>& roll, int id) {
for (Student& s : roll) {
if (s.id == id) { return &s; }
}
return nullptr; // the honest answer
}
// const version for read-only callers
const Student* findByName(const std::vector<Student>& roll,
const std::string& name) {
for (const Student& s : roll) {
if (s.name == name) { return &s; }
}
return nullptr;
}
// A pointer parameter says "this argument is optional"
void report(const Student* s) {
if (s == nullptr) {
std::cout << "No such student.\n";
return; // the check is mandatory
}
std::cout << s->name << " (#" << s->id << ") avg " << s->average << "\n";
}
// A reference parameter says "this must exist"
void awardBonus(Student& s, double points) {
s.average = std::min(100.0, s.average + points);
}
int main() {
std::vector<Student> roll{
{"Ada", 1001, 88.5},
{"Alan", 1002, 74.0},
{"Grace", 1003, 96.25},
{"Edsger", 1004, 81.75},
};
std::cout << std::fixed << std::setprecision(2);
// Found: check before use, every time
if (Student* found = findById(roll, 1002)) { // C++17 if-with-initialiser
awardBonus(*found, 5.0); // * turns the pointer into a ref
report(found);
}
// Not found: the null path is exercised, not crashed
report(findById(roll, 9999));
// A const pointer for reading only
if (const Student* g = findByName(roll, "Grace")) {
std::cout << g->name << " has " << g->average << "\n";
// g->average = 100.0; // ERROR: read-only, as intended
}
// Pointer arithmetic over the vector's contiguous storage
const Student* begin = roll.data();
const Student* end = begin + roll.size();
double total{0.0};
for (const Student* p = begin; p != end; ++p) { // ++p steps one Student
total += p->average;
}
std::cout << "Class average: " << total / roll.size() << "\n";
// Adding a student may reallocate: every pointer above is now suspect.
roll.push_back({"Barbara", 1005, 91.0});
// begin, end and found may all dangle here. Re-fetch, never reuse.
std::cout << "Now " << roll.size() << " students\n";
return 0;
}
The signatures are the lesson. findById returns Student* because "no match" is a real outcome and only a pointer can carry it; report takes a pointer for the same reason and checks it on the first line. awardBonus takes Student& because a bonus for nobody is meaningless, so *found converts the pointer back into a guaranteed-present reference at the call site. The if (Student* found = ...) form scopes the pointer to the branch where it is known good, which is the C++17 idiom for lookups. The data() loop shows subscripting and pointer arithmetic are the same operation. And the final push_back is there to make the invalidation rule concrete: pointers into a vector are only as durable as the vector's buffer.
Common Mistakes
- Dereferencing a null or uninitialised pointer. The first crashes, the second corrupts.
- Forgetting to check for
nullptrbefore*porp->x. - Returning the address of a local variable. It dangles the moment the function returns.
- Keeping a pointer into a vector across an insertion. Reallocation invalidates it.
- Confusing
*in a declaration with*in an expression. They are unrelated jobs. - Writing
int* a, b;and expecting two pointers. Onlyais one. - Using
(*p).xwherep->xreads better — both work, but the arrow is idiomatic. - Calling
deleteon a pointer that did not come fromnew, or twice on the same one. - Using
NULLor0instead ofnullptr.
Best Practices
- Initialise every pointer, to
nullptrif you have nothing yet. - Check before dereferencing, and use
if (T* p = find(...))to scope the pointer to where it is valid. - Prefer references when the target must exist. Reserve pointers for genuinely optional things.
- Never own memory through a raw pointer. Use
std::vector,std::string,std::unique_ptr. - Use
const T*when a function only reads through the pointer. - Set a pointer to
nullptronce it is stale, so misuse crashes loudly instead of silently. - Build with
-fsanitize=address,undefinedduring development. It catches most pointer errors precisely.
Practice Exercises
- Swap by pointer: Write
void swap(int* a, int* b)that rejects null arguments, then compare it line by line with the reference version and note which you would rather read. - Optional lookup: Given a
std::vector<std::string>, write a function returningconst std::string*— the match, ornullptr. Call it once for a hit and once for a miss, handling both. - See the invalidation: Take a pointer to
v[0], print it,push_backtwenty elements, print the pointer andv.data()again, and record whether the address moved. Then rerun under-fsanitize=addresswith a write through the stale pointer. - Declare all four combinations for an
int value:int* p,const int* pc,int* const cpandconst int* const cpc. For each one, try both*x = 99andx = &other, comment out whatever fails, and record the compiler's message. Then write down the rule you used to read each declaration — and check it againstint const* q, which is one of the four in disguise. - Write
int sum(const int* data, std::size_t count)and call it three ways: with a raw array, withv.data()andv.size(), and with&v[2]and3to sum a slice. Then printsizeof(arr)insidemainandsizeof(data)inside the function, explain the difference in a comment, and rewrite the signature to take astd::span<const int>so the size can no longer be passed wrongly.