Double Pointers
Challenge Gallery
Quick Reference
Double pointer patterns:
// Modify a caller's pointer
void alloc(int **pp) {
*pp = calloc(10, sizeof(int));
}
int *arr = NULL;
alloc(&arr); // arr is now allocated
// 2D array allocation
int **grid = calloc(rows, sizeof(int *));
for (int i = 0; i < rows; i++)
grid[i] = calloc(cols, sizeof(int));
Indirection levels:
| Expression | Type | Value |
|---|---|---|
pp |
int ** |
Address of p |
*pp |
int * |
Address of x |
**pp |
int |
Value of x |
Common Pitfalls
- Modifying a copy –
void f(int *p) { p = malloc(...); }changes a local copy. Useint **to change the caller’s pointer. - Forgetting to free rows – 2D arrays need each row freed before the row-pointer array.
- Dereferencing NULL – Always check that *pp is not NULL before accessing **pp.