Reputation: 397
Why this swap method didn't work
void swap(int *x,int *y){
int *temp;
temp = x;
x = y;
y = temp;
}
Why? I think it's same as the common one..
Upvotes: 0
Views: 146
Reputation: 69027
x
and y
behave just like local variables.
your code is swapping x
and y
values, not the values they point to.
Upvotes: 1
Reputation: 145839
C passes function arguments by value: you are only swapping copies of pointers.
If you want to swap two int
:
void swap(int *x,int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Upvotes: 3
Reputation: 3911
You are swapping the addresses stored in temporary pointers on the stack, not the values stored in the memory they point to. You want to do this instead:
void swap(int *x,int *y){
int temp = *x;
*x = *y;
*y = temp;
}
Upvotes: 1