Pointers in C: solved pass-by-reference exercises

  2 minutes

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

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

#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;
}
Before: x=12, y=45
After: x=45, y=12

Also test equal values:

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

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

  • address operator &,
  • dereference operator *,
  • pass-by-reference in C,
  • modifying external values from a function.
  • Passing x instead of &x.
  • Using uninitialized pointers.
  • Confusing *p (value) with p (address).
  • Calling broader pointer APIs with NULL without defensive checks.
  • Time: O(1).
  • Extra space: O(1).

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

If you want a complete path with progressive difficulty:

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

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

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