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
Expected output
Recommended edge case
Also test equal values:
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
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.