/* Lecture #5 Demo * * Swap * * A function uses pointers to swap the contents of two integers. */ #include /* swap() swaps the values of two integer locations. * Note that swap's parameters are two integer *pointers*, so it must be * passed the *address* of locations in memory containing the integers. */ void swap (int *px, int *py) { int temp = *px; /* Temp gets *contents* pointed to by px. */ *px = *py; /* Location pointed to by px gets value */ /* pointed to by py -- note that the */ /* addresses in px and py are not */ /* changing here. */ *py = temp; /* Move the val originally pointed to by */ /* px into location pointed to by py. */ } int main() { int x = 50, y = 100; printf("x = %d, y = %d\n", x, y); swap(&x, &y); /* swap requires pointers to x and y, */ /* so we must pass not the values of x */ /* and y, but rather the *addresses* of */ /* x and y. */ printf("x = %d, y = %d\n", x, y); return 0; }