1

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.

4

3 回答 3

5

您的函数按值接受指针,因此它所做的任何修改在返回后都将不可见。实际上,您正在交换指针副本的值。

于 2013-08-28T21:33:25.830 回答
4

你想做的是std::swap

template <class T> void swap ( T& a, T& b )
{
  T c(a); a=b; b=c;
}
于 2013-08-28T21:39:35.930 回答
1

当您使用相同的变量名称来表示两个不同的事物时,您几乎总是会使您自己的工作变得更加困难。

在你的函数之外x,是一个int.
你的函数里面x是一个pointer-to-int.
那是你困惑和麻烦的根源。

我下面的代码不会交换变量的地址。
(确实,我认为这是不可能的;编译器决定 . 的地址x。您无法更改它。
您只能更改存储在该地址的值。)

但我认为这就是你想要的:

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;
}
于 2013-08-28T21:49:40.473 回答