C Workshop · Swap with Pointers
Lesson C

Swap with Pointers

To swap two variables in a function you must pass their addresses. Otherwise the function only swaps copies.

What it is

To swap two variables inside a helper, the helper must receive their addresses. Otherwise it only swaps copies, and main’s x and y never notice. After a real swap, 3 and 7 become 7 and 3.

Approach

  1. Write swap(int *a, int *b) using a temporary.
  2. Call swap(&x, &y).
  3. Print x and y.

Where this is used in the real world

Diagram

1

x=3 y=7

before

2

swap(&x,&y)

call

3

*a ↔ *b

write

4

7 3

after

Run algorithm

Each step highlights the matching C line. Program output appears only when a line that prints actually runs.

Ready
C code
1#include <stdio.h>
2void swap(int *a, int *b) {
3    int t = *a;
4    *a = *b;
5    *b = t;
6}
7int main(void) {
8    int x = 3, y = 7;
9    swap(&x, &y);
10    printf("%d %d\n", x, y);
11    return 0;
12}
What this line does
Press Run algorithm. The highlight will move through the C code.
Program output
(no output yet)

Check your understanding

Five questions. Pick one answer each, then Check answers. The correct choice turns green.

1. After swap, x y print:

Swapped.

2. Why &x and &y?

Pass addresses.

3. int t = *a copies:

Temp.

4. A swap of copies (no pointers) would:

Need pointers.

5. swap is void because:

Out-parameters.