I'm trying to write a function that takes two pointers as arguments and then makes the first pointer point to the object the second pointer was pointing to and the second to the object pointed to by the first.
void swap(int *x, int *y)
{
int *s;
s = x;
x = y;
y = s;
}
In the main function, I'll do something like
int x, y;
swap(&x, &y);
std::cout << &x << " " << &y << std::endl;
But it seems like the addresses don't change.
If instead I dereference the pointers and try to change the values, the values are swapped as expected. I'm wondering why this function won't change where the pointers point to.
Your function accepts the pointers by value, so any modification it makes will not be visible after it returns. In effect you are swapping the values of copies of the pointers.
You will almost always make your own work more difficult when you use the same variable name to mean two different things.
Outside your function,
x
is anint
.Inside your function
x
is apointer-to-int
.That is the source of your confusion and trouble.
My code below does not swap the addresses of the variables.
(indeed, I believe that is impossible; The compiler decides the address of
x
. You cannot change that.You can only change the value stored at that address.)
But I think this is what you want:
What you're trying to do is
std::swap