Module 2 · Memory
2.3Pointers
A pointer is a variable that holds the address of another object. Learn & and *, nullptr, the -> operator, const with pointers and a first look at pointer arithmetic, and when to pick a pointer over a reference.
On this page
- Key terms
- In 30 seconds
- Addresses, & and *
- nullptr: a pointer to nothing
- ->: fields through a pointer
- Pointers vs references
- const and pointers
- Pointer arithmetic: a first look
- Which one should I use?
- Under the hood
- Common pitfalls
- Following nullptr
- Returning the address of a local variable
- Printing a pointer directly
- Try it yourself
Key terms
- pointer (
T*) - A variable that holds the address of an object of type
T. You can change which object it points at. - address-of (
&x) - The operator that gives the address of
x. Written before a value, not after a type. - dereference (
*p) - Following a pointer to the object it points at.
*pis that object. nullptr- The value of a pointer that points at nothing.
- null pointer dereference
- Using
*or->on a pointer that isnullptr. It's undefined behavior. ->- Reaches a field through a pointer:
p->lengthmeans(*p).length. const T*- A pointer you can read through but not change the object through. The pointer itself can be pointed somewhere else.
T* const- A pointer that can't be pointed at another object. The object can still be changed through it.
void*- A pointer to an object of unknown type.
std::printlnprints one as an address. - pointer arithmetic
- Adding to or subtracting from a pointer to move between elements that sit next to each other in memory.
A reference is a second name for one object, fixed when it’s created and never empty. That covers most cases, but not all. Sometimes the honest answer is “there’s no object”: a search that found nothing. And sometimes you need to step from one object to the next. A pointer handles both: it’s a variable that holds the address of an object, so it can be empty, and it can be changed to point somewhere else.
In 30 seconds
int* p = &x;stores the address ofxinp.*pisxitself.- A pointer can hold
nullptr, meaning “no object”, and you can change where it points. A reference can do neither. p->lengthreads a field of the objectppoints at.- Using
*onnullptris undefined behavior. Check a pointer before you follow it.
Addresses, & and *
Every object sits at some address in memory, as Stack, heap and lifetime showed. Put & in front of a variable to get its address, and store that in a pointer: a variable whose type is written with * after the pointed-at type. Put * in front of the pointer to get back to the object, which is called dereferencing.
#include <print>
int score = 10;
int* p = &score; // p holds the address of score
*p += 5; // *p is score
std::println("{} {}", score, *p);Output
15 15
Unlike a reference, p is a real variable of its own, holding a number (8 bytes on this platform). & and * each mean two things, depending on where they appear:
| Symbol | After a type | Before a value |
|---|---|---|
& | int& is a reference type | &score is the address of score |
* | int* is a pointer type | *p is the object p points at |
You can print an address. std::println prints it in hexadecimal if you first turn the pointer into a void*, a pointer to an unknown type, with static_cast. The address changes from run to run, so your output will differ:
#include <print>
int score = 10;
int* p = &score;
std::println("{}", static_cast<void*>(p));Output from one run (it varies)
0x7ffd8c3a1e40
nullptr: a pointer to nothing
A pointer can hold nullptr, which means it points at no object. That makes a pointer a good return type for a search that might find nothing. Before you follow the pointer, compare it with nullptr:
#include <print>
#include <vector>
double* find_below(std::vector<double>& values, double limit) {
for (double& v : values) {
if (v < limit) {
return &v;
}
}
return nullptr;
}
int main() {
std::vector<double> quality = {38.5, 36.0, 12.5, 40.0};
double* low = find_below(quality, 20.0);
if (low != nullptr) {
std::println("first low score: {}", *low);
}
if (find_below(quality, 5.0) == nullptr) {
std::println("no score below 5");
}
}Output
first low score: 12.5 no score below 5
You can also write if (low): a pointer counts as true when it isn’t nullptr.
Common pitfallAlways give a pointer a value
A local int* p; without a value holds whatever bits that memory had before. Using it is undefined behavior. Write int* p = nullptr; if you don’t have an object yet.
->: fields through a pointer
When a pointer points at a struct, you could write (*p).length to read a field: follow the pointer, then pick the field. That’s common enough to have its own operator, ->:
#include <print>
#include <string>
struct Read {
std::string name;
int length;
};
int main() {
Read read{"read_7", 150};
Read* p = &read;
p->length = 151;
std::println("{} {}", (*p).name, p->length);
}Output
read_7 151
Pointers vs references
A pointer and a reference both let you reach an object without copying it. The difference is in what you’re allowed to do with them:
Reference (int& r = x;) | Pointer (int* p = &x;) | |
|---|---|---|
| Can be empty | No | Yes, nullptr |
| Must refer to an object when created | Yes | No, but always give it a value |
| Can be pointed at another object | No | Yes, p = &y; |
| Reaching the object | r | *p |
| Reaching a field | r.length | p->length |
Passing x to a function | f(x) | f(&x) |
Assigning to a reference changes its object. Assigning to a pointer changes where it points:
#include <print>
int a = 1;
int b = 2;
int* p = &a;
*p = 10; // changes a
p = &b; // p now points at b
*p = 20; // changes b
std::println("{} {}", a, b);Output
10 20
const and pointers
A pointer involves two things, the pointer and the object it points at, so const can apply to either. Read the type from right to left: int* const p is “p is a const pointer to an int”, and const int* p is “p is a pointer to a const int”.
| Declaration | Change the object through it? | Point it at another object? |
|---|---|---|
int* p | Yes | Yes |
const int* p | No | Yes |
int* const p | Yes | No |
const int* const p | No | No |
const int* is the one you’ll use most. It’s the pointer version of const int&: you can look but not change.
int total = 0;
const int* view = &total;
*view = 10;The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:3:7: error: assignment of read-only location ‘* view’
3 | *view = 10;
| ~~~~~~^~~~int* const stops the pointer from being pointed somewhere else:
int a = 1;
int b = 2;
int* const fixed = &a;
fixed = &b;The compiler rejects this
main.cpp: In function ‘int main()’:
main.cpp:4:7: error: assignment of read-only variable ‘fixed’
4 | fixed = &b;
| ~~~~~~^~~~Pointer arithmetic: a first look
The elements of a std::vector sit next to each other on the heap. If a pointer points at one element, adding 1 moves it to the next one, and subtracting two pointers into the same vector gives how many elements apart they are:
#include <print>
#include <vector>
std::vector<int> pixels = {10, 20, 30, 40};
int* p = &pixels[1];
std::println("{}", *p);
p = p + 1;
std::println("{} {}", *p, *(p + 1));
std::println("{}", p - &pixels[0]);Output
20 30 40 2
Adding 1 moves the pointer by one element, not one byte: for an int, that’s 4 bytes here. Reading through a pointer outside the elements is undefined behavior, and so is moving it before the first element or more than one past the last. Arrays, std::array and std::span shows the sanitizer catching it, and std::span, which does this job more safely.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
A reference (T&, const T&) | There’s always an object: most function parameters. | It can’t be empty, so there’s nothing to check, and the call site stays plain. | void f(const Read& r), called as f(read) |
A pointer (T*, const T*) | “No object” is a valid answer, or you need to move it to other objects. | nullptr says “nothing” clearly, and you can point it somewhere else. | const Read* find(...), then if (p) |
A value (T) | Small types, or the function needs its own copy. | No address to follow, and nothing can dangle. | int count(...) |
Rule of thumb: use a reference when there’s always an object, and a pointer only when “nothing” is a real possibility or the pointer has to move. A plain pointer should never be in charge of freeing memory: that’s what std::vector and the smart pointers in Smart pointers are for.
Pointers also hold the addresses of heap memory you ask for with new; Lesson 2.5, Dynamic memory and RAII, covers it.
Under the hood
A pointer is a number: the address of the first byte of its object. On this platform (64-bit Linux) every pointer is 8 bytes, whatever it points at, because every address is the same size:
#include <print>
std::println("{} {} {}", sizeof(char*), sizeof(int*), sizeof(double*));Output
8 8 8
The type of a pointer tells the compiler what’s at the address: how many bytes to read for *p, and how far p + 1 moves. That’s how p + 1 knows to move 4 bytes for an int* and 8 bytes for a double*.
On this platform, nullptr is stored as the address 0. The operating system never gives a program memory at address 0, so reading from it can’t succeed. Without sanitizers, the program usually crashes with a “segmentation fault”.
As References showed, the compiler stores a reference as an address too. A reference and a pointer usually compile to the same machine code; the difference is in the rules the compiler enforces for you.
PerformanceFollowing a pointer costs a memory read
*p reads from wherever p points. If that memory isn’t in the CPU’s cache, the read is slow. Data reached through many separate pointers is slower to work through than the same data stored side by side in a std::vector. Module 9 covers caches.
Common pitfalls
Following nullptr
Using * or -> on a null pointer is undefined behavior. The compiler can’t tell that a search will come back empty, so this compiles; the sanitizer stops it when it runs:
#include <print>
#include <vector>
int* find_negative(std::vector<int>& values) {
for (int& v : values) {
if (v < 0) {
return &v;
}
}
return nullptr;
}
int main() {
std::vector<int> changes = {3, 1, 4};
int* first = find_negative(changes);
int value = *first;
std::println("{}", value);
}This fails when it runs
main.cpp:16:17: runtime error: load of null pointer of type 'int'
Check before you follow the pointer:
#include <print>
#include <vector>
int* find_negative(std::vector<int>& values) {
for (int& v : values) {
if (v < 0) {
return &v;
}
}
return nullptr;
}
int main() {
std::vector<int> changes = {3, 1, 4};
if (int* first = find_negative(changes)) {
std::println("{}", *first);
} else {
std::println("no negative change");
}
}Output
no negative change
Undefined behaviorA null pointer won't always crash
Without sanitizers, reading through nullptr usually crashes, but the compiler is allowed to assume it never happens, and optimized code can do something stranger. Build with -fsanitize=address,undefined while you learn; Setting up shows how.
Returning the address of a local variable
A function’s locals are destroyed when it returns, so their addresses are useless to the caller. This is the pointer version of the dangling reference from References, and the compiler catches it the same way:
#include <print>
int* bigger(int a, int b) {
int result = a > b ? a : b;
return &result;
}
int main() {
std::println("{}", *bigger(3, 7));
}The compiler rejects this
main.cpp: In function ‘int* bigger(int, int)’:
main.cpp:5:12: error: address of local variable ‘result’ returned [-Werror=return-local-addr]
5 | return &result;
| ^~~~~~~
main.cpp:4:9: note: declared here
4 | int result = a > b ? a : b;
| ^~~~~~
cc1plus: all warnings being treated as errorsReturn the value instead: int bigger(int a, int b).
Printing a pointer directly
std::println won’t print an int*, so it can’t print an address by accident when you meant the value. The error comes from deep inside the library and is long; look for the line ending in required from here, which points at your code, and the phrase std::formatter must be specialized:
#include <print>
int score = 10;
int* p = &score;
std::println("{}", p);The compiler rejects this
In file included from /usr/include/c++/15/print:43,
from main.cpp:1:
/usr/include/c++/15/format: In instantiation of ‘class std::__format::_Checking_scanner<char, int*>’:
/usr/include/c++/15/format:4809:4: required from ‘consteval std::basic_format_string<_CharT, _Args>::basic_format_string(const _Tp&) [with _Tp = char [3]; _CharT = char; _Args = {int*&}]’
| __scanner(_M_str);
| ^~~~~~~~~
main.cpp:5:14: required from here
5 | std::println("{}", p);
| ^~~~
/usr/include/c++/15/format:4627:10: error: static assertion failed: std::formatter must be specialized for each type being formatted
| (is_default_constructible_v<formatter<_Args, _CharT>> && ...),
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/include/c++/15/format:4627:10: note: ‘std::is_default_constructible_v<std::formatter<int*, char> >’ evaluates to false
compilation terminated due to -fmax-errors=1.Write *p to print the value, or static_cast<void*>(p) to print the address.
Try it yourself
Try it yourself
Finish find_max so it returns a pointer to the largest value. It already returns nullptr when the vector is empty. If the largest value appears twice, point at the first one.
#include <print>
#include <vector>
const int* find_max(const std::vector<int>& values) {
if (values.empty()) {
return nullptr;
}
// Your code here: return a pointer to the largest value.
return nullptr;
}
void report(const std::vector<int>& values) {
const int* best = find_max(values);
if (best == nullptr) {
std::println("no values");
} else {
std::println("max {} at index {}", *best, best - &values[0]);
}
}
int main() {
report({12, 40, 7, 40, 3});
report({});
}Expected output
max 40 at index 1 no values
Show a hint
Start best at &values[0], loop with const int& v, and move best to &v when v is bigger than *best.
Show a solution
#include <print>
#include <vector>
const int* find_max(const std::vector<int>& values) {
if (values.empty()) {
return nullptr;
}
const int* best = &values[0];
for (const int& v : values) {
if (v > *best) {
best = &v;
}
}
return best;
}
void report(const std::vector<int>& values) {
const int* best = find_max(values);
if (best == nullptr) {
std::println("no values");
} else {
std::println("max {} at index {}", *best, best - &values[0]);
}
}
int main() {
report({12, 40, 7, 40, 3});
report({});
}find_max returns a const int* because it only reads the vector, and nullptr is its answer for an empty vector. report checks for nullptr before following the pointer, and best - &values[0] counts how many elements best is past the first.
Saved in this browser only.