我有一个问题,我无法创建一个简单的程序来使用指针交换两个变量。我这样试过:
int main() {
int x=5, y=10;
int *p=nullptr;
p=&x;
y=*p;
x=y;
cout<<x<<" "<<y;
}
我该怎么办?
最佳答案
void swap(int *x, int *y)
{
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
int main()
{
int a = 7, b = 3;
std::cout << a << ' ' << b << '\n';
swap(&a, &b);
std::cout << a << ' ' << b << '\n';
}
同时考虑 std::swap
关于c++ - 如何用指针交换两个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43235909/