交换两个指针 [英] Swapping two pointers

查看:112
本文介绍了交换两个指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数使用两个指针作为参数,然后使第一个指针指向第二个指针指向的对象,第二个指针指向第一个指针指向的对象.

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.

这篇关于交换两个指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆