如何在带有签名的函数内交换指针地址?
假设:
int weight, height;
void swap(int* a, int* b);
所以在退出这个函数后,实际参数(weight
和height
)的地址会改变。有可能吗?
最佳答案
如果你想交换指针指向的地址,而不仅仅是存储在该地址的值,你需要通过引用(或指向指针的指针)传递指针。
#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/