void swap(int *x, int *y){
int* temp;
temp = x;
x = y;
y = temp;
}
swap()这里有两个指针,int但在内部只交换本地指针的值x和y- 它们指向的对象的地址。swap()- 表示在它返回之前的末尾,x指向已指向的对象y,并y指向已指向的对象x。
x调用者对对象和y指向没有影响。
如果你想交换x和y指向的对象的值,你需要这样定义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