pointers-memory · beginner · ~15 min

Swap two pointers via a function

Understand pointer-to-pointer to mutate caller variables.

Challenge

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.

Task

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.

Input

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.

Output

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.

Example

int x = 1, y = 2;
int *px = &x, *py = &y;
swap_ptrs(&px, &py);    ->   px now points to y, py now points to x

Edge cases

  • a == b (same address): a no-op (the value swaps with itself).
  • Either int* is NULL: still works, just swaps the NULL across.

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 int **, each the address of a caller int* (which may be NULL).

Output format

No return value; the caller's two pointers are 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.