Code:
#include <stdio.h>
void int_swap(int*, int*);
int main(int argc, char **argv) {
int x=2, y=3, z=4;
//we did nothing until here, so value is normal 2,3,4;
printf( "main: x=%2d, y=%2d, z=%2d\n", x, y, z);
//we are going to swap 2 with 3 (x and y);
int_swap(&x, &y);
//not it should print 3, 2, 4;
printf( "main: x=%2d, y=%2d, z=%2d\n", x, y, z);
//going to swap 3 and 4 (x and z);
int_swap(&x, &z);
//now it should print 4, 2, 3;
printf( "main: x=%2d, y=%2d. z=%2d\n", x, y, z);
//swap 2 and 4 (y and x);
int_swap(&y, &x);
//now it should print 2, 4, 3;
printf( "main: x=%2d, y=%2d, z=%2d\n", x, y, z);
getchar();
return 0;
}
void int_swap( int *x, int *y ) {
int t;
t = *x;
*x = *y;
*y = t;
/*
first time: swapping 2 and 3; x = 2, y = 3;
t = 2;
x = 3;
y = 2 (t - our temporary variable);
second time: swapping 3 and 4; x = 3; z = 4;
t = 3;
x = 4;
z = 3 (t - our temporary variable);
third time: swapping 2 and 4; y = 2; x = 4;
t = 2 (LOOK HERE, YOU PASSED Y FIRST, SO T IS POINTING TO Y) NO MATTER IF THE NAME IS *x
HE IS POINTING TO Y LOOK AT THE POSITION.
*/
}
}
I think I understand your error:
look here:
to your calc be right, you should pass x first