Skip to main content

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.c
void 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:

  1. Save the value at *a into a temporary variable temp.
  2. Overwrite *a with the value at *b.
  3. Overwrite *b with the saved value from temp.

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.