I'd strongly recommend that you run this through the debugger, which will show you what is happening.
But ... start by looking at your code:
int x=1, y=2; ----- This x is never used.
int main(){
int x=3; ----- This version of x hides the outer one;
func(&y, &x); ----- passes pointers to "2" and "3" respectively.
In the function, the outside world names are ignored:
void func(int *x, int *y){ --- So x points to "2" and y points to "3"
x=y; --- Now x and y both point to the same place,
which contains "3"
*x=*x-2; --- So both x and y now point to "3 - 2", or "1"
*y=*y*2; --- And both x and y now point to "1 * 2" or "2"
printf("x=%2d y=%2d\n", *x, *y); --- So you get "x = 2, y = 2" printed.
}
When you get back to
main
both x and y contain "2" - because
func
never used the original value of the
x
pointer you passed in - it overwrote it instead.
Break out the debugger, and follow your code through - it'll become a whole load clearer!
How you use it depends on your compiler system, but a quick Google for the name of your IDE and "debugger" should give you the info you need.
Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.