Pointers: swap two numbers in C
Pass addresses to a function so it can change the caller’s variables. Press Run to try it, then change the code and run it again.
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main(void) {
int x = 5, y = 10;
printf("Before: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After: x = %d, y = %d\n", x, y);
printf("x lives at address %p\n", (void *)&x);
return 0;
}
Output
Press Run to see the output.
More C examples
- Hello, World · The classic first C program.
- Sum of two numbers · Read two numbers with scanf and print their sum.
- Check a prime number · Test whether a number is prime by trying divisors up to its square root.
- Sort an array (bubble sort) · Sort numbers by swapping neighbours until nothing moves.
- Structs and malloc · Build a small linked list on the heap, print it and free it.