Write a function swap() that swaps two integers using pointers, and call it from main().
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main(void) {
int a = 10, b = 20;
printf("Before: a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("After: a = %d, b = %d\n", a, b);
return 0;
}
Before: a = 10, b = 20 After: a = 20, b = 10
The function receives the addresses of a and b, so writing through *a and *b changes the caller's variables. A swap that takes plain ints would only swap its own copies.