ft_swap — Swap Two Integers
Allowed functions: none
Write a function that swaps the contents of two integers the addresses of which are passed as parameters.
void ft_swap(int *a, int *b);
Solution
Download ft_swap.cvoid ft_swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}
How It Works
Goal: Swap the values of two integers using their memory addresses.
Approach: Store one value in a temporary variable, then overwrite and restore using pointer dereferencing.
Step by step:
- Save the value at
*ainto a temporary variabletemp. - Overwrite
*awith the value at*b. - Overwrite
*bwith the saved value fromtemp.
Key concept: Pointers and pass by reference — since C passes arguments by value, you must pass pointers (addresses) to modify variables from inside a function.