我对这两个功能感到困惑:
void Swap_byPointer1(int *x, int *y){
int *temp=new int;
temp=x;
x=y;
y=temp;
}
void Swap_byPointer2(int *x, int *y){
int *temp=new int;
*temp=*x;
*x=*y;
*y=*temp;
}
为什么Swap_byPointer2
在x和y之间交换成功,而Swap_byPointer1
没有?
最佳答案
在您的第一个函数中,您正在交换指针本身,而在第二个函数中,您正在交换指针指向的值,即取消引用的指针。
如果你想改变一个指针指向的东西,你应该将一个指针传递给一个指针(即int**x
)并改变第二个指针。
像这样
void Swap_byPointer1(int **x, int **y){
int *temp;
temp=*x;
*x=*y;
*y=*temp;
}
关于c++ - 通过指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8230173/