Pointers and References (C++ Core #2)
Pointers are addresses with a type. References are aliases that cannot be
rebound. Almost every tricky question in this area comes from one of three
things: which part of a declaration is const, how an array turned into a
pointer, and how big sizeof says things are.
Pointers and pointer arithmetic
A pointer stores an address. The type tells the compiler how many bytes one step is and how to interpret the bytes at that address.
int a[5] = {10, 20, 30, 40, 50};
int* p = a; // same as &a[0]
std::cout << *p; // 10
std::cout << *(p + 2); // 30
std::cout << p[2]; // 30 (p[2] is *(p + 2))
p += 3; // moves by 3 * sizeof(int) = 12 bytes
std::cout << *p; // 40
long diff = &a[4] - &a[1]; // 3, type ptrdiff_t
The arithmetic scales by the pointee size. p + 1 is not “the next byte”, it is
“the next int”. On a 64-bit machine, int* p; p + 1 advances 4 bytes, and
double* q; q + 1 advances 8.
Valid pointer values for an array a of n elements: a through a + n. The
one-past-the-end pointer is legal to form and compare; dereferencing it is UB.
Anything beyond that is UB even to compute.
int a[3] = {1, 2, 3};
int* end = a + 3; // legal, do not dereference
for (int* q = a; q != end; ++q) std::cout << *q; // 123
void* is an untyped address: it holds any object pointer, but you cannot
dereference it or do arithmetic on it (in standard C++; GCC allows void* + 1 as
an extension, which is exactly the kind of thing an exam asks about).
sizeof(int*) on a 64-bit platform, and why is p + 1not the same as (char*)p + 1?
ASolution
8 bytes. p + 1 advances by sizeof(int) because the pointer’s type determines
the stride; (char*)p + 1 advances by one byte.
References
A reference is a new name for an existing object. It must be initialized, it cannot be rebound, and it has no null state of its own.
int x = 1;
int& r = x; // r refers to x
r = 2; // x is now 2
int& s = r; // s also refers to x
int y = 3;
r = y; // assigns 3 to x; r still refers to x, not y
That last line is the key difference from a pointer: assignment through a reference writes the referred object, it does not retarget the reference.
int* p = &x;
p = &y; // p now points to y
*p = 4; // y becomes 4
References are usually implemented as pointers under the hood, but the language gives them value semantics. A reference member or a reference return type keeps that binding for its whole life.
| Pointer | Reference | |
|---|---|---|
| Can be null | yes | no (a valid reference always refers to an object) |
| Can be rebound | yes | no |
Needs * to access |
yes | no |
| Address of the variable itself | p |
&r gives the referent’s address |
| Arithmetic | yes | no |
| Uninitialized | yes (bad) | no, must bind |
A reference to a temporary extends the temporary’s lifetime when bound to a
const reference or an rvalue reference:
const std::string& s = std::string("hello"); // temporary lives as long as s
ASolution
The local’s storage ends when the function returns, so the reference dangles.
Compilers warn about this (-Wreturn-local-addr), and using it is UB.
Null pointers
nullptr is a value of type std::nullptr_t that converts to any pointer type.
NULL is a macro for 0 (or __null in GCC), and plain 0 also works.
int* p = nullptr;
int* q = NULL; // usually 0
int* r = 0;
if (!p) { } // true
p = &x;
if (p) { } // true
Use nullptr, not NULL or 0. The reason is overload resolution:
void f(int);
void f(char*);
f(NULL); // ambiguous or picks f(int), depending on NULL's definition
f(nullptr); // picks f(char*), no ambiguity
Dereferencing a null pointer is UB. So is *p where p is a null pointer passed
to a function that forgot the check. Comparing and testing are fine.
delete p; require p to be non-null?ASolution
No. delete nullptr is a no-op by definition. delete on an uninitialized or
already-freed pointer is the problem.
Dangling pointers and references
A pointer or reference is dangling when the object it refers to no longer exists. The variable still holds the old address, so it looks valid.
int* bad() {
int x = 5;
return &x; // x dies at return
}
int& alsoBad() {
int x = 5;
return x; // same problem, reference version
}
int* p = new int(7);
delete p; // p is now dangling
*p = 8; // use-after-free, UB
Other common sources:
- A
std::vectorreallocates and invalidates pointers/iterators into it. - A
std::stringis modified and its internal buffer moves (for long strings). - A lambda captures by reference and outlives the captured variable.
- A pointer to a stack object is stored somewhere and used after the function returns.
There is no runtime check. Sanitizers (-fsanitize=address) catch many of these
in testing; they cannot prove absence in production.
ASolution
Both descriptions fit: the pointer value is indeterminate for use, and the object it used to point to is gone. Reading through it is use-after-free, which is UB.
Double pointers
A pointer to a pointer has two jobs: modifying a caller’s pointer, and representing a dynamically allocated 2D array (as an array of pointers).
void allocate(int** out, int n) {
*out = new int[n]; // writes the caller's pointer
}
int* data = nullptr;
allocate(&data, 10);
data[0] = 1;
delete[] data;
Without the extra level, the function would only modify its own copy:
void broken(int* out) { out = new int[10]; } // leaks, caller unchanged
int** is not a 2D array. A real 2D array int a[3][4] is one contiguous
block, and it decays to int (*)[4] (pointer to array of 4 ints), not int**.
Passing int** where int (*)[4] is expected is a type error, and casting
between them produces wrong addressing.
\begin{tikzpicture}[font=\rmfamily, >=stealth,
b/.style={draw, thick, minimum width=1.0cm, minimum height=0.55cm, font=\scriptsize},
a/.style={->, thick}]
\node[b, fill=blue!10] (pp) at (0,0) {int**};
\node[b, fill=orange!15] (p) at (2.2,0) {int*};
\node[b, fill=green!18] (v) at (4.4,0) {int};
\draw[a] (pp) -- (p);
\draw[a] (p) -- (v);
\node[font=\scriptsize, anchor=north] at (0,-0.5) {address of a pointer};
\node[font=\scriptsize, anchor=north] at (2.2,-0.5) {address of an int};
\node[font=\scriptsize, anchor=north] at (4.4,-0.5) {value};
\end{tikzpicture}
void f(int** m) not accept int a[3][4]?ASolution
a decays to int (*)[4], a pointer to a 4-int array. int** is a pointer to
a pointer, a different type with different arithmetic. The compiler rejects it.
Const correctness, and the three const pointer forms
const applies to the thing immediately to its left, or to the type on its left
if there is nothing to its left. Read declarations right to left.
const int* p1; // pointer to const int
int const* p2; // same thing
int* const p3 = &x; // const pointer to int
const int* const p4 = &x; // const pointer to const int
| Declaration | Can change *p? |
Can change p? |
|---|---|---|
int* p |
yes | yes |
const int* p |
no | yes |
int* const p |
yes | no |
const int* const p |
no | no |
int x = 1, y = 2;
const int* p = &x;
*p = 5; // error: *p is const
p = &y; // fine: the pointer itself is not const
int* const q = &x;
*q = 5; // fine
q = &y; // error: q is const
const int* const r = &x;
*r = 5; // error
r = &y; // error
The rule generalizes: const on the pointee is about what you can modify
through the pointer; const on the pointer is about whether the pointer value
can change.
void print(const std::string& s); // read-only, no copy
void mutate(std::string& s); // may modify
void maybe(std::string* s); // may be null, may modify
const member functions make this a pointer to const, which is why they can be
called on const objects and cannot modify members (unless the member is
mutable).
Removing const with const_cast compiles. Writing through the result is UB if
the original object was defined const (it may live in read-only memory).
p in int* const p = &x;?ASolution
A const pointer to int. The pointee is mutable; the pointer value cannot
change. const binds to p, not to int.
Passing by value, reference, and pointer
Passing by value, passing by reference, and passing by pointer are the three modes, and they differ in cost, in what the caller sees, and in whether null is possible.
void byValue(int x) { x = 99; } // copy; caller unchanged
void byRef(int& x) { x = 99; } // alias; caller changed
void byPtr(int* x) { if (x) *x = 99; }// address; caller changed if non-null
int a = 1;
byValue(a); // a == 1
byRef(a); // a == 99
byPtr(&a); // a == 99 (if byRef ran first, a was already 99)
Choose by intent:
| Intent | Signature |
|---|---|
| read a small value | void f(int x) |
| read a large object | void f(const Big& x) |
| modify the caller’s object | void f(Big& x) |
| optional argument, may be absent | void f(Big* x) (check null) |
| transfer ownership | void f(std::unique_ptr<Big> x) |
By value is safest: the function cannot affect the caller. By reference is the
cheapest way to read a large object. By pointer is the C-style optional
parameter, and it makes the null case explicit at the call site (f(nullptr)).
Const reference to a temporary extends its lifetime, so f(Big{}) works with
const Big& but not with Big&.
void f(const std::vector<int>& v) usually better thanvoid f(std::vector<int> v)?
ASolution
The reference avoids copying every element. The copy version is fine for small vectors or when the function needs its own modifiable copy.
Arrays versus pointers, and decay
An array is a contiguous block with a known size. In most expressions it decays to a pointer to its first element, losing the size.
int a[5] = {1, 2, 3, 4, 5};
int* p = a; // decay: &a[0]
sizeof(a); // 20 on a 32-bit int platform
sizeof(p); // 8 (pointer size)
sizeof(*p); // 4 (int)
Decay happens in function arguments, arithmetic, comparisons, and almost every
context except sizeof, &, decltype, and binding to a reference to array.
void f(int a[]) { sizeof(a); } // 8: parameter is int*
void g(int (&a)[5]) { sizeof(a); } // 20: reference to the array keeps the size
template <size_t N>
void h(const int (&a)[N]) { /* N is known */ }
2D arrays decay one dimension at a time:
int m[3][4];
m; // int (*)[4] — pointer to array of 4 ints
m[0]; // int* — pointer to first int
m[1][2]; // int
sizeof(m); // 48
sizeof(m[0]); // 16
&a has type int (*)[5] and points to the whole array, so &a + 1 jumps 20
bytes, while a + 1 jumps 4.
String literals are arrays of const char with a null terminator:
const char* s = "hi"; // points at a static array {'h','i','\0'}
char t[] = "hi"; // copies into a local array of 3 chars
sizeof("hi"); // 3, including '\0'
\begin{tikzpicture}[font=\rmfamily, >=stealth,
c/.style={draw, thick, minimum width=0.8cm, minimum height=0.6cm, font=\scriptsize\bfseries}]
\foreach \v [count=\i from 0] in {1,2,3,4,5} \node[c, fill=blue!10] at (\i*0.85,0) {\v};
\node[font=\scriptsize, anchor=east] at (-0.3,0) {a:};
\node[c, fill=orange!20] at (0,0) {1};
\draw[->, thick, red!65] (2.5,-0.9) -- (0.35,-0.35);
\node[font=\scriptsize, anchor=north] at (2.5,-0.9) {pointer stores the address of a[0]};
\node[font=\scriptsize, anchor=north] at (2.0,-1.55) {the array itself is the five cells, not the pointer};
\end{tikzpicture}
void f(int a[10]), what is sizeof(a)?ASolution
The size of a pointer (8 on 64-bit). The 10 is documentation only; the
parameter type is int*.
Function pointers
A function pointer stores the address of a function. The signature is part of the type.
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int (*op)(int, int) = add; // declaration
std::cout << op(3, 4); // 7
op = sub;
std::cout << op(3, 4); // -1
using BinOp = int (*)(int, int);
BinOp table[] = {add, sub};
std::cout << table[1](9, 2); // 7
The parentheses around *op are required. Without them, int* op(int,int) is a
function returning int*.
Function pointers are used for callbacks and dispatch tables. std::function is
the modern alternative: it can hold lambdas with captures and member functions,
at the cost of type erasure and possible allocation.
#include <functional>
std::function<int(int,int)> f = [](int a, int b) { return a * b; };
// C-style callback
void qsort(void* base, size_t n, size_t size,
int (*cmp)(const void*, const void*));
Member function pointers are a separate type (int (Foo::*)(int)) and need an
object to call. They are rarely needed in an OA, but the syntax shows up in
interview trivia.
pointer?
ASolution
A capturing lambda has state, so the call needs a this-like pointer to that
state. A function pointer carries only an address. Use std::function or a
non-capturing lambda.
Deep: const forms, decay, and sizeof
These three are the most common confusion in predict-the-output questions. A checklist:
Const forms. Read the declaration from the identifier outward:
int const * p; // p is a pointer to const int
int * const p; // p is a const pointer to int
const int * const p; // const pointer to const int
const int* and int const* are the same. int* const is not.
Decay. Anything that turns T[N] into T*:
- passing to a function with a pointer parameter
a + 1,a[i],a == preturn a;from a function returningT*- assigning to
T* std::cout << a(prints the address, because ofconst void*overload)
Places where it does not decay: sizeof a, &a, decltype(a) (gives
int[5]), binding int (&)[5], and std::begin(a) (template deduction keeps the
array).
sizeof. Compile-time size in bytes. It does not evaluate its operand:
int i = 0;
sizeof(i++); // 4, and i stays 0
sizeof(int); // 4 (usually)
sizeof(char); // 1, always
sizeof("abc"); // 4: 'a','b','c','\0'
sizeof(std::string); // implementation detail (often 32), not the text length
In C, sizeof('a') is sizeof(int) (4) because character constants have type
int. In C++, sizeof('a') is 1 because the constant has type char. That
difference is a real exam question.
| Expression | Value on x86-64 |
|---|---|
sizeof(int) |
4 |
sizeof(long) |
8 (LP64) |
sizeof(long long) |
8 |
sizeof(void*) |
8 |
sizeof(int[10]) |
40 |
sizeof(int*) |
8 |
sizeof(struct {char c; int i;}) |
8 (padding, Ch. 8) |
char s[] = "hello"; — what are sizeof(s), strlen(s), andsizeof(&s)?
ASolution
6, 5, and 8. sizeof counts the terminator, strlen does not, and &s is a
pointer (to the whole array), so it is pointer-sized.
Bugs and edge cases
- Uninitialized pointers.
int* p; *p = 1;writes to a random address. Initialize tonullptror a real object. - One-past-end dereference.
a + nis valid to form, invalid to read. - Pointer arithmetic on non-arrays. Subtracting pointers into different objects is UB, even if the addresses are close.
- Returning addresses of locals. Compiles, dangles. Return by value or use
heap/
std::unique_ptr. - Losing
const.const int* p; int* q = p;does not compile without a cast; the cast then enables UB. sizeofon a parameter. Arrays decay, so you get 8, not the array size.- Function-pointer syntax.
int (*f)(int)is a function pointer;int* f(int)is a function returning a pointer. - Mismatched
new[]/delete.deleteon an array is UB; usedelete[](Ch. 3).
const int* p and you need to pass an int*.What happens, and what about the reverse?
ASolution
int* to const int* is an implicit, safe conversion. const int* to int*
is an error: it would allow writing through a const pointer. const_cast is
the explicit (and dangerous) escape hatch.
Next: Memory Management (C++ Core #3) — stack, heap, ownership, and the smart
pointers that make delete mostly unnecessary.