c++ - 通过指针

标签 c++ pointers

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

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/

相关文章:

c++ - 在C++和OpenCV中调用其他文件中的函数

java - 我可以封装同一个类的对象之间的成员吗?

java.lang 在 JNI 中调用 BluetoothAdapter.getDefaultAdapter() 时抛出 UNsatisfiedLinkError

c++ - 从 constexpr 数组获取 constexpr 属性时遇到困难

c、求指针数组的长度

链表段错误的C++数组

c++ - mingw 构建错误 : undefined reference to `__chkstk_ms'

c - C 中的垃圾值

c - 在函数中使用指针访问二维数组

c++ - 如何创建可以影响通过构造函数传递的对象的类变量?