gpt4 book ai didi

c++ - 通过指针

转载 作者:IT老高 更新时间:2023-10-28 21:39:15 27 4
gpt4 key购买 nike

我对这两个功能感到困惑:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com