Lecture 1: Pointers in C++
A pointer is an object that stores the address of another object. Almost every pointer bug comes from mixing up which of the two objects you are touching, or from using a target that is no longer alive.
Next: Lecture 2 - Object Oriented Data Types · Lecture 3 - Linked List. Pointers are the foundation for both.
1. Mental model
int x = 37;
int* p = &x; // p holds x's address
*p = 85; // x is now 85
Two separate objects, linked only by the address stored in p:
flowchart LR
p["p<br/>value: 0x1000"] -->|points to| x["x (at 0x1000)<br/>value: 85"]
| Expression | Meaning |
|---|---|
x |
the int itself |
&x |
address of x |
p |
stored address (same as &x) |
*p |
the object p points to (x) |
&p |
address of the pointer variable itself |
* has two jobsIn a declaration int* p, * means “pointer to”. In an expression *p, it means “dereference”. Same symbol, different roles.
Declaration gotcha: the * binds to each declarator, not the type.
int* p, q; // p is int*, q is plain int!
Declare one variable per line.
Reading and writing through a pointer
int num = 78;
int* p = #
std::cout << *p; // read: 78
*p = 24; // write: num is 24, p still holds &num
Writing through p changes the target. The address stored in p does not change.
Trace it
int x = 10; int* p = &x;
*p += 5; // x = 15
x *= 2; // x = 30
std::cout << *p;
Answer: 30. p still points to x, so it sees the updated value.
2. Pointer states
stateDiagram-v2
[*] --> Null: = nullptr
Null --> Valid: p = &x
Valid --> Dangling: x's lifetime ends
Valid --> Null: p = nullptr
- Null: deliberately points at nothing. Initialise with
nullptr(C++11). An uninitialised local pointer holds an indeterminate value. - Valid: points to a live object.
- Dangling: the target is gone.
p != nullptrwill not catch this. - Never dereference
nullptror a dangling pointer (undefined behaviour).
int* p = nullptr;
int x = 7;
p = &x;
if (p != nullptr) std::cout << *p; // guard against null
3. Aliasing and copying
Copying a pointer copies the address, so both now refer to the same object.
int a = 10, b = 20;
int* p = &a;
int* q = p; // alias: q -> a
p = &b; // retarget p only
*p = 99; // b = 99; q STILL points to a
Equality: p == q compares addresses; *p == *q compares values.
int a = 5, b = 5;
int* p = &a; int* q = &b;
p == q; // 0 different addresses
*p == *q; // 1 same values
4. Arrays and pointer arithmetic
- An array is consecutive elements.
int* p = a;points toa[0]. p + nmoves by n elements, i.e.n * sizeof(*p)bytes. You never count bytes yourself.last - firstgives the number of elements between them (typestd::ptrdiff_t). It is only valid for pointers into the same array.- One-past-the-end (
a + size) is legal to form and compare, but never to dereference.a + size + 1is already invalid.
int a[] = {10, 20, 30, 40};
int* p = a;
++p; // a[1] -> 20
p += 2; // a[3] -> 40
Illustrative addresses (assuming sizeof(int) == 4):
| a[0] | a[1] | a[2] | a[3] |
|---|---|---|---|
0x1000 |
0x1004 |
0x1008 |
0x100C |
| 10 | 20 | 30 | 40 |
The index goes up by 1 while the address goes up by 4.
Subtraction counts elements
int* first = a; // 0x1000
int* last = a + 3; // 0x100C
last - first; // 3 (elements), not 12 (bytes)
Traversal
int sum = 0;
for (int* p = a; p != a + 3; ++p) sum += *p; // 60
It gives loops a clean stop condition (p != end) without needing a valid element to compare against. The loop stops before dereferencing it.
Array practice
int a[] = {2,4,6}; int* p = a; int* q = p + 2; *p = 10;
*q= 6q - p= 2 elementsa[0]= 10
5. Pointers and functions
Pass-by-value copies the pointer, but the copy still points to the same target.
void set100(int* p) { if (p) *p = 100; }
int x = 0;
set100(&x); // x == 100
| Goal | Signature | Effect |
|---|---|---|
| Modify the pointed-to object | void f(int* p) → *p = 100 |
caller’s variable changes |
| Re-aim the caller’s pointer | void f(int*& p) → p = nullptr |
caller’s pointer changes |
| Re-aim, passing by value | void f(int* p) → p = nullptr |
only the local copy changes |
Does reset(int* p) { p = nullptr; } null the caller’s pointer?
No. It only changes the local copy. Use int*& (“reference to a pointer to int”) to rebind the caller’s pointer.
Pointer vs reference parameter: both can modify the caller’s object, but a pointer can be null (an “optional” argument). A reference always names a real object.
Returning pointers
Safe only if the target outlives the function, for example pointing into the caller’s array:
int* find(int* a, int n, int key) {
for (int i = 0; i < n; ++i)
if (a[i] == key) return &a[i];
return nullptr; // not found
}
Precondition: a has at least n accessible elements.
double* bad() { double s = 26.48; return &s; } // s dies at return
The returned pointer dangles. Fix: return the value when the caller just needs a value:
double good() { return 26.48; }
6. Pointers to structs and classes
structmembers default to public;classmembers default to private. Otherwise they are the same.- Member access:
- object →
student.gpa - pointer →
p->gpa, equivalent to(*p).gpa *p.gpais a bug:.binds tighter than*.
- object →
- Access control still applies through a pointer:
p->set(5)works on public methods, but private data stays private.
Student student;
Student* p = &student;
student.gpa = 3.9; // dot with an object
p->gpa = 3.7; // arrow with a pointer
7. Templates
A class template is one definition reused for many types. The compiler generates a separate class for each type used.
template <typename T>
class Number {
T num;
public:
explicit Number(T n) : num(n) {}
T get() const { return num; }
};
Number<int> a(7); // distinct types:
Number<double> b(7.7); // Number<int> != Number<double>
- Operations follow the rules of
T:Calculator<int>(5,2).divide()gives2(integer division), whileCalculator<double>(5.0,2.0).divide()gives2.5. divide()needs a nonzero divisor.- The template argument is part of the type, so
Number<double>* q = &n;(wherenis aNumber<int>) is a compile error.
8. Ownership: unique_ptr
- Raw pointers are best for observing existing objects. They don’t own anything.
std::unique_ptrexpresses exclusive ownership of a dynamically allocated object, and frees it automatically.
#include <memory>
auto p = std::make_unique<int>(42);
std::cout << *p; // 42; freed automatically at scope exit
unique_ptr is C++11. make_unique is C++14.
Quick self-test
Why is badSalary() a bug?
salary is a local variable whose lifetime ends when the function returns, so the returned pointer dangles. Return the value instead.
What is the difference between p == q and *p == *q?
p == q compares addresses. *p == *q compares the values they point to. Two different ints holding 5 have equal values but unequal pointers.
Why can’t Number<int>* point to a Number<double>?
The template argument is part of the type, so they are two unrelated types.
Cheat sheet
- Pointer = address;
&gets it,*follows it. - Copying a pointer creates an alias, not a new object.
p + nmoves in elements, and the one-past pointer may be compared but not dereferenced.- The target must be alive for every access (no pointers to dead locals).
->for pointers,.for objects.- Templates create a distinct type per argument.