Pointers to Pointers & Pointer Types
A pointer to a pointer adds one more hop. It is how functions modify a caller's pointer and how dynamic arrays of strings are managed.
In plain English
A pointer to a pointer is a sign that points to another sign, which points to the house.
Multi-level indirection
int **pp declares a pointer to a pointer to int. pp stores the address of a pointer variable; *pp is that pointer; **pp is the int it points to. Every level must be valid before you dereference it. Multi-level pointers appear in argv, dynamic 2-D arrays, and functions that allocate or replace a pointer for the caller.
int x = 42;
int *p = &x;
int **pp = &p;
printf("%d\n", **pp); /* 42 */
**pp = 7;
printf("%d\n", x); /* 7 */const and complex declarations
The position of const matters. const int *p means the pointed-to int cannot be changed through p; int *const p means the pointer itself cannot change. Reading complex declarations from the inside out helps: start at the identifier, then apply * and [] and () according to precedence. Function pointers and pointers to arrays follow the same rules.
const int *p1; /* pointer to const int */
int *const p2 = &x; /* const pointer to int */
/* read from the inside out */
int (*fp)(int); /* pointer to function taking int, returning int */Key takeaways
- int **pp is a pointer to a pointer to int.
- Every indirection level must be valid before dereference.
- const placement changes what is protected.
- Read complex declarations from the identifier outward.
Common pitfalls
- Dereferencing a NULL intermediate pointer.
- Misreading const placement.
- Confusing a pointer to an array with an array of pointers.
Key focus
- Trace **pp and *pp carefully.
- Know the difference between pointer-to-const and const-pointer.
Quick check
1. If pp is an int ** pointing to p, and p points to x, what is **pp?
2. What does const int *p mean?