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
#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
Before: x=12, y=45
After: x=45, y=12Recommended edge case
Also test equal values:
Before: x=7, y=7
After: x=7, y=7This 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
xinstead of&x. - Using uninitialized pointers.
- Confusing
*p(value) withp(address). - Calling broader pointer APIs with
NULLwithout 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.
Recommended next exercise
- Struct in C: solved exercise with arrays of structs
- Malloc and free in C: solved dynamic memory exercise
- Binary search in C: solved exercise on sorted arrays
- All C exercises
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.