pointers-memory · intermediate · ~9 min

Swap two pointers

Mutate pointers through pointers-to-pointers.

Challenge

Exchange two pointers held by the caller, so each ends up pointing where the other did. The pointed-to int values are left in place.

Task

Implement void swap_ptrs(int **a, int **b) that swaps the two int* values at *a and *b. No main — the grader calls it.

Input

a and b — addresses of two int* variables in the caller.

Output

No return value. After the call, *a and *b hold each other's former values.

Example

int x = 1, y = 2;
int *p = &x, *q = &y;
swap_ptrs(&p, &q)   ->   p points to y (*p == 2), q points to x (*q == 1)

Why this matters

Drill: practice one contract before combining it with other skills.

Input format

a and b — addresses of two int* variables in the caller.

Output format

No return value. After the call, *a and *b hold each other's former values.

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.

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