pointers-memory · beginner · ~15 min

Swap two pointers via a function

Understand pointer-to-pointer to mutate caller variables.

Challenge

Implement void swap_ptrs(int **a, int **b) that swaps the two int* pointers the caller holds.

Why this matters

Swapping two pointers via a function is the most direct demonstration that C is pass-by-value — to mutate a caller's pointer, you need a pointer to that pointer.

Input format

Two non-NULL int **.

Output format

The caller sees the pointers swapped.

Constraints

No allocations. No data dereferenced — just swap the pointers themselves.

Starter code

void swap_ptrs(int **a, int **b) { /* TODO */ }

Common mistakes

Swapping *a and *b instead of a and b (changes the pointed-to values, not the pointers). Using a temporary of the wrong type (int t instead of int *t).

Edge cases to handle

Both pointers alias (a == b) — swap is a no-op. Either pointer is NULL — swap still works, just swaps NULLs around.

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.