pointers-memory · intermediate · ~15 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)

Input format

a, b — addresses of two int* variables.

Output format

No return value; the two pointers are swapped.

Constraints

Swap the pointers, not the int values they point to.

Starter code

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

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