C Programming: Memory, Pointers and the Stack ยท Functions and Scope
C copies arguments. A swap function only works when it gets pointers to the caller's variables.
#include <stdio.h>
void swap_copy(int a, int b) {
int t = a;
a = b;
b = t;
}
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int main(void) {
int x = 1, y = 2;
swap_copy(x, y);
printf("after swap_copy: %d %d\n", x, y);
swap(&x, &y);
printf("after swap: %d %d\n", x, y);
return 0;
}x is created on the stack with the value 1. y is created on the stack with the value 2.t is created on the stack with the value 1.a changes from 1 to 2.swap_copy() has finished, so its variables are gone.t is created on the stack with the value 1.y changes from 2 to 1.swap() has finished, so its variables are gone.after swap: 2 1.0.