c++ - 传递指针地址

标签 c++ pointers

int main()
{
  int x = 2, y = 4;
  func(&x, &y);
  printf("%d %d\n", x, y);
  return 0;
}

void func(int *x, int *y)
{
  int *temp;
  temp = x;
  x = y;
  y = x;
}

你好

对于这段代码,我不知道为什么输出是 2 4 而不是 4 4。因为 func() 中的 x = y 意味着 x 现在指向 y 的地址,而 func() 中的 y = x 现在意味着 y指向 x(即 y)的地址,两个变量现在都已经指向 y。

非常感谢!

最佳答案

答案很简单:您更改了 func 中的指针值 - 但不是它们指向的值。我猜您想交换变量(由于 temp var)。

这段代码应该可以工作(交换值):

void func(int *x, int *y)
{
    int temp = *x; // dereferencing the pointer to get the value it points at.
    *x = *y;
    *y = temp;
}

保持您最初的期望(由于第二次分配,这在代码方面没有任何意义):

void func(int *x, int *y)
{
    *x = *y;
    *y = *x;
}

关于c++ - 传递指针地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5753980/

相关文章:

c++ - 在 C++ 中从 double 更改为 long double 不再给出正确的结果

c++ - xcode构建错误: Semantic issue cast from pointer to smaller type 'int' loses information

C++ 容器行为

c++ - 如何在 C++ 中创建良好的上下文类/返回引用?

c - 带地址的数组

c++ - Cmake 重新生成变量变化

c++ - 如何从已编译的C文件(使用Borland C++编译)中查看程序代码

c++ - 在 C++ 中返回对象或指针

GSL ODE 求解器的 C++ 类成员函数

c - 指针和动态数组的大小