#include<stdio.h>
void xingcan(int x,int y)
{
int i;
i=x;
x=y;
y=i;
printf("xingcanwei:\n%d\n%d\n",x,y);
}
int main()
{
int a=11,b=22;
xingcan(a,b);
printf("shicanwei:\n%d\n%d\n",a,b);
return 0;
}
xingcanwei:
22
11
shicanwei:
11
22
--------------------------------
Process exited after 0.0111 seconds with return value 0
Press any key to continue . . .
--------------------------------------------------------------------------------------------------------------------------
由程序的运行结果可知形参的改变不会对实参产生影响,及形参与实参是完全不同的变量,或者说形参是实参的临时拷贝;
若想要在函数中对实参进行修改,可以通过传址的方式将实参的地址传给形参,程序修改如下
--------------------------------------------------------------------------------------------------------------------------#include<stdio.h>
void xingcan(int* px,int* qy)
{
int i;
i=*px;
*px=*qy;
*qy=i;
printf("xingcanwei:\n%d\n%d\n",*px,*qy);
}
int main()
{
int a=11,b=22;
xingcan(&a,&b);
printf("shicanwei:\n%d\n%d\n",a,b);
return 0;
}
xingcanwei:
22
11
shicanwei:
22
11
--------------------------------
Process exited after 0.01026 seconds with return value 0
Press any key to continue . . .
可以看到,通过传址的方式可以在函数中对实参进行修改