Swapping two numbers using pointers
What you'll learn: How to use pointers to allow a function to modify variables belonging to another part of your program.
The Postcard Problem
Imagine you want a friend to come over and rearrange the furniture in your living room. If you send them a photo of your room, they can draw where the sofa should go, but your actual sofa hasn't moved. This is how normal functions work in C: they receive a "photo" (a copy) of your data.
To actually move the furniture, you don't send a photo; you send your home address. With the address, your friend can enter the real room and move the real sofa. In C, pointers are that address.
Swapping by Reference
When we want a function to swap two numbers, we must pass their memory addresses using the address-of operator (&). Inside the function, we use the dereference operator (*) to go to those addresses and change the values stored there.
Here is how you swap two integers:
#include <stdio.h>
// The function takes two pointers (addresses)
void swap(int *a, int *b) {
int temp;
temp = *a; // Go to address a, get the value, put it in temp
*a = *b; // Go to address b, get the value, put it at address a
*b = temp; // Put the temp value at address b
}
int main() {
int x = 10;
int y = 20;
// Pass the addresses of x and y using &
swap(&x, &y);
printf("x: %d, y: %d", x, y); // Output: x: 20, y: 10
return 0;
}
Why the temp variable?
Think of swapping as having a glass of orange juice and a glass of milk. To swap them, you need a third, empty glass (the temp variable). You pour the juice into the empty glass, pour the milk into the first glass, and finally pour the juice from the empty glass into the second one.
The Magic of Pointers
Without pointers, the swap function would only swap copies of x and y. The moment the function ended, those copies would vanish, and the original x and y in main would remain unchanged. By passing pointers, we give the function "permission" to reach back into the main function's memory and perform the swap on the original variables.
Key takeaway
Passing pointers to a function allows that function to permanently modify the original variables by working with their memory addresses.