pointers-memory · beginner · ~9 min
Understand pointer-to-pointer to mutate caller variables.
Swap the two int* pointers that a caller holds, by taking their addresses. Because C passes arguments by value, mutating the caller's pointers requires a pointer to each pointer.
Implement void swap_ptrs(int **a, int **b) so that after the call the pointer formerly in *a is in *b and vice versa. No main — the grader calls it.
a and b, each the address of an int* variable in the caller. The pointed-to int* values may be NULL; a and b may be the same address.
No return value. After the call, the two int* values have been exchanged. The pointed-to int data is never touched — only the pointers move.
int x = 1, y = 2;
int *px = &x, *py = &y;
swap_ptrs(&px, &py); -> px now points to y, py now points to x
a == b (same address): a no-op (the value swaps with itself).int* is NULL: still works, just swaps the NULL across.Transfer exercise: apply the lesson to a complete function contract.
a and b, each the address of an int* variable in the caller. The pointed-to int* values may be NULL; a and b may be the same address.
No return value. After the call, the two int* values have been exchanged. The pointed-to int data is never touched — only the pointers move.
a and b are valid addresses of writable int* variables; a may equal b. Their inner pointer values may be NULL. Exchange only pointer values, never targets.
void swap_ptrs(int **a, int **b) { /* TODO */ }
Swapping **a and **b, which mutates the integers and can dereference NULL.
Same outer pointer; equal inner values; either or both inner values NULL; target integers remain unchanged.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.