/* This is a useless program designed to introduce you to pointers. To compile: gcc -o 03-swap 03-swap.c -Wall To run: ./03-swap C. Andrews 2015-02-17 */ #include /* This function is attempting to swap the values in x and y. Internally, the swap happens, but this does not affect the variables used to call the function. C is pass by value, so we don't have access to the original variables, just the values. */ void swap1(int x, int y){ printf("[swap1] before: x %d y %d\n", x, y); int tmp = x; x = y; y = tmp; printf("[swap1] after: x %d y %d\n", x, y); } /* Our second try takes in pointers (i.e., the addresses to locations holding values we want swapped). This allows us to reach into memory and swap the locations of the original variables. */ void swap2(int * xp, int * yp){ printf("[swap2] before: x %d y %d\n", *xp, *yp); int tmp = *xp; *xp = *yp; *yp = tmp; printf("[swap2] after: x %d y %d\n", *xp, *yp); } int main(int argc, char * argv[]){ int x = 1; int y = 2; // this attempt doesn't work printf("[main] before: x %d y %d\n", x, y); swap1(x,y); printf("[main] after: x %d y %d\n", x, y); printf("\n"); // this time we pass the addresses of the values we want swapped, so it does work printf("[main] before: x %d y %d\n", x, y); swap2(&x,&y); printf("[main] after: x %d y %d\n", x, y); return 0; }