pointers-memory · beginner · ~9 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

Transfer exercise: apply the lesson to a complete function contract.

Input format

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 format

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.

Constraints

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.

Starter code

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

Common mistakes

Swapping **a and **b, which mutates the integers and can dereference NULL.

Edge cases to handle

Same outer pointer; equal inner values; either or both inner values NULL; target integers remain unchanged.

Complexity

O(1).

Background lessons

Up next

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