Swapping two pointers [duplicate]

2020-07-30 00:39发布

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.

标签: c++ pointers
3条回答
Anthone
2楼-- · 2020-07-30 00:48

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.

查看更多
来,给爷笑一个
3楼-- · 2020-07-30 00:58

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 an int.
Inside your function x is a pointer-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:

void swap(int *ptr_x, int *ptr_y)
{
    int temp;
    temp = *ptr_x;
    *ptr_x = *ptr_y;
    *ptr_y = temp;
}

int main(void)
{
    int x=5, y=9;
    swap(&x, &y);
    std::cout << &x << " " << &y << std::endl;  // Sorry, Address of X and Y will always be the same
    std::cout << x << " " << y << std::endl;  // Now x is 9 and y is 5.

    return 0;
}
查看更多
冷血范
4楼-- · 2020-07-30 01:13

What you're trying to do is std::swap

template <class T> void swap ( T& a, T& b )
{
  T c(a); a=b; b=c;
}
查看更多
登录 后发表回答