Pointers in C: solved pass-by-reference exercises

Pointers in C: solved exercise

If you came from pointers in C solved exercises, this page targets a core skill: changing values from a function via pass-by-reference.

Problem statement

Create a swap function that receives two integers by reference and swaps them. Print values before and after.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <stdio.h>

void swap(int *a, int *b) {
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

int main(void) {
    int x = 12;
    int y = 45;

    printf("Before: x=%d, y=%d\n", x, y);
    swap(&x, &y);
    printf("After: x=%d, y=%d\n", x, y);

    return 0;
}

Expected output

1
2
Before: x=12, y=45
After: x=45, y=12

Also test equal values:

1
2
Before: x=7, y=7
After: x=7, y=7

This confirms behavior is still correct when no visible change occurs.

What this exercise teaches

  • address operator &,
  • dereference operator *,
  • pass-by-reference in C,
  • modifying external values from a function.

Common mistakes

  • Passing x instead of &x.
  • Using uninitialized pointers.
  • Confusing *p (value) with p (address).
  • Calling broader pointer APIs with NULL without defensive checks.

Time and space complexity

  • Time: O(1).
  • Extra space: O(1).

Practical use

This pattern is everywhere in performance-critical code and systems software where you need in-place updates without copying large data.

Guided practice and next step

If you want a complete path with progressive difficulty:

FAQ

Is this good as a first C pointers exercise?

Yes. It is one of the first exercises you should master before dynamic memory and linked lists.

Where should I continue practicing?

Continue with Programming in C in 100 Solved Exercises and Kindle Unlimited option: View on Amazon.

How should I practice this exercise type to improve faster?

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.