Swapping through pointers
swap gets two pointers whose arrows lead back into main's frame. Writing through *x and *y changes a and b themselves.
Without pointers, swap would only get copies and main would never see the change.
#include <stdio.h>
void swap(int *x, int *y) {
int tmp = *x;
*x = *y;
*y = tmp;
}
int main(void) {
int a = 1;
int b = 2;
swap(&a, &b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
Output:
a = 2, b = 1
From the lesson: Pointers