4

当我们以这种方式修改交换函数时会发生什么?我知道它不起作用,但到底发生了什么?我不明白我实际上做了什么?

#include <stdio.h>

void swap(int*, int*);

int main(){
   int x=5,y=10;
   swap(&x, &y);
   printf("x:%d,y:%d\n",x,y);
   return 0;
 }

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

3 回答 3

8

在函数中

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

您只需交换两个函数参数的指针值。

如果你想交换它们的值,你需要像这样实现它

void swap(int* x, int* y){ 
    int temp = *x;  // retrive the value that x poitns to
    *x = *y;        // write the value y points to, to the memory location x points to
    *y = temp;      // write the value of tmp, to the memory location x points to
}

这样,swap 函数会交换引用的内存位置的值。

于 2020-04-06T10:17:18.397 回答
5
void swap(int *x, int *y){ 
   int* temp;
   temp = x;
   x = y;
   y = temp;
}

swap()这里有两个指针,int但在内部只交换本地指针的值xy- 它们指向的对象的地址。swap()- 表示在它返回之前的末尾,x指向已指向的对象y,并y指向已指向的对象x

x调用者对对象和y指向没有影响。


如果你想交换xy指向的对象的值,你需要这样定义swap()

void swap(int *x, int *y){ 
   int temp;
   temp = *x;     // temp gets the int value of the int object x is pointing to.
   *x = *y;       // x gets the int value of the int object y is pointing to.
   *y = temp;     // y gets the int value of temp (formerly x).
}

示例程序(在线示例):

#include <stdio.h> 

void swap(int *x, int *y){ 
   int temp;
   temp = *x;     // temp gets the int value of the int object x is pointing to.
   *x = *y;       // x gets the int value y of the int object y is pointing to.
   *y = temp;     // y gets the int value of temp (formerly x).
}

int main (void)
{
    int a = 1, b = 2;
    printf("Before the swap() function:\n");
    printf("a = %d b = %d\n\n",a,b);

    swap(&a,&b);

    printf("After the swap() function:\n");
    printf("a = %d b = %d",a,b);

    return 0;
}

输出:

Before the swap() function:
a = 1 b = 2

After the swap() function:
a = 2 b = 1
于 2020-04-06T10:27:56.453 回答
4

在函数内,它的两个参数交换了传递参数值的副本。

由于该函数处理参数的副本,因此不会交换作为临时对象的原始参数(传递给 x 和 y 的指针)。

要交换指向 x 和 y 的指针的值,您必须在 main 中定义这样的指针,通过 x 和 y 的地址初始化它们,并通过指向指针的指针将它们传递给函数。

这是一个演示程序。

#include <stdio.h>

void swap( int **ppx, int **ppy )
{
    int *tmp = *ppx;
    *ppx = *ppy;
    *ppy = tmp;
}

int main(void) 
{
    int x=5, y=10;

    int *px = &x;
    int *py = &y;

    printf( "*px = %d, *py = %d\n", *px, *py );

    swap( &px, &py );

    printf( "*px = %d, *py = %d\n", *px, *py );

    return 0;
}

它的输出是

*px = 5, *py = 10
*px = 10, *py = 5

另请参阅我对这个问题的回答Pointer Confusion: swap method in c

于 2020-04-06T10:18:43.457 回答