为什么即使我使用指针,我的代码也不交换变量的值?

Why doesn't my code swap the value of the variables even when I make use of pointers?

#include<stdio.h>
void mystery(int *ptra, int *ptrb) 
{
   int *temp;
   temp = ptrb;
   ptrb = ptra;
   ptra = temp;
}
int main() 
{
    int a=2016, b=0, c=4, d=42;
    mystery(&a, &b);
    if (a < c)
        mystery(&c, &a);
    mystery(&a, &d);
    printf("%d\n", a);
}

我试图通过使用指针来交换变量的值,但我不明白为什么即使在函数调用之后变量仍包含相同的值

您需要更改指针指向的内容,而不是指针本身。

void mystery(int *ptra, int *ptrb) 
{
   int temp; //make it non-pointer also.
   temp = *ptrb;
   *ptrb = *ptra;
   *ptra = temp;
}

如果您更改指针本身,更改将是函数局部的,因为变量 ptraptrb 是局部变量,保存地址。

请记住,一般来说,当您处理指针时,通常会涉及 两个 个对象:

  • 指针本身
  • 指针指向的对象,即内容

在你的例子中,你处理的是指针,而不是内容——指针本身是按值传递的,这就是为什么对指针变量的更改是函数局部的。

另外,请注意已经有 std::swap 可以完成这项工作。如果您不知道它,请改用它。

在您的 mystery 函数中,您实际访问指针指向的值时需要使用的表示法是:

*ptra

这叫做解引用指针。我有一个关于那个的旧答案 here

所以:

void mystery(int *ptra, int *ptrb) 
{
   int temp = *ptrb;
   *ptrb = *ptra;
   *ptra = temp;
}

您不是在交换指针指向的变量的值,而是在交换地址。

在指针旁边使用 * 以使用值而不是地址。