代码:
#include <stdio.h> void swap(int x,int y)
{
int temp; temp = x;
x = y;
y = temp;
printf("In swap: x = %d,y = %d\n",x,y);
} void swap_with_pt(int * x,int * y)
{
int temp; temp = *x;
*x = *y;
*y = temp;
printf("In swap_with_pt: x = %d,y = %d\n",*x,*y);
} int main()
{
int x = ,y = ; printf("Before swap: x = %d,y = %d\n",x,y);
swap(x,y);
printf("After swap: x = %d,y = %d\n",x,y);
printf("-------------------------------\n");
printf("Before swap_with_pt: x = %d,y = %d\n",x,y);
swap_with_pt(&x,&y);
printf("After swap_with_pt: x = %d,y = %d\n",x,y); return ;
}
输出:
Before swap: x = 5,y = 10
In swap: x = 10,y = 5
After swap: x = 5,y = 10
---------------------------------
Before swap_with_pt: x = 5,y = 10
In swap_with_pt: x =10,y = 5
After swap_with_pt: x = 10,y = 5
解释:
swap函数调用时首先创建x,y的变量副本,我们姑且称之为x2,y2(其实名字依然是x和y,只不过这里的x和y只在swap函数里有意义),并将main函数中x,y的值传给变量x2,y2,然后函数交换了x2,y2的值,运行完函数后x2,y2变量生命期结束。所以,x和y的值是不变的。
swap_with_pt函数调用时同样创建x,y的指针的变量副本,我们姑且称之为x2,y2(其实名字依然是x和y,只不过这里的x和y只在swap_with_pt函数里有意义),并将x,y的地址值传给x2,y2,这个时候x2和y2是指向main函数中x,y的,然后通过*运算修改x,y的值。注意,“*+指针名”是可以改变它所指向的变量的值的。