c++ - 在 C++ 中交换指针地址

标签 c++ pointers

如何在带有签名的函数内交换指针地址?

假设:

int weight, height;
void swap(int* a, int* b);

所以在退出这个函数后,实际参数(weightheight)的地址会改变。有可能吗?

最佳答案

如果你想交换指针指向的地址,而不仅仅是存储在该地址的值,你需要通过引用(或指向指针的指针)传递指针。

#include <cassert>
void swap(int*& a, int*& b)
{
    int* c = a;
    a = b;
    b = c;
}

int main()
{
    int a, b;
    int* pa = &a;
    int* pb = &b;

    swap(pa, pb);

    assert(pa == &b);  //pa now stores the address of b
    assert(pb == &a);  //pb now stores the address of a
}

或者您可以使用 STL 交换函数并将指针传递给它。

#include <algorithm>

std::swap(pa, pb);

不过,你的问题似乎不是很清楚。

关于c++ - 在 C++ 中交换指针地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1826203/

相关文章:

c++ - Ubuntu : apt-get install <package> equivalent in C++ apt-pkg library

c++ - 在循环中创建线程 vector 的问题

pointers - 隐藏 nil 值,理解为什么 golang 在这里失败

c - C 中的 2D 数组指针访问段错误

c - c中的链表添加到前面

c++ - 在类中使用时,[this] 和 [&] 在 lambda 捕获列表中是否等效?

c++ - 放松内存排序时,C++延迟会增加

c++ - Qt 中的 SQLite 验证

c++ - 坚持定义静态指针并使用它

c - For循环创建顺序名称txt文件