函数----交换数值
原创
©著作权归作者所有:来自51CTO博客作者普热希缇的原创作品,请联系作者获取转载授权,否则将追究法律责任
错误:
#include<stdio.h>
void Swap1 (int x,int y)//形参
{
int tmp = 0;//定义一个临时变量
tmp = x;
x = y;
y = tmp;
}
int main()
{
int a = 10;
int b = 30;
printf("a=%d , b=%d",a,b);
Swap1(a,b);//实参
printf("a=%d , b=%d",a,b);
return 0;
}
正确:
#include<stdio.h>
void Swap2 (int* pa,int* pb)
{
int tmp = 0;//定义一个临时变量
tmp = *pa;
*pa = *pb;
*pb = tmp;
}
int main()
{
int a = 10;
int b = 30;
printf("a=%d , b=%d",a,b);
Swap2(&a,&b);//交换a,b;
printf("a=%d , b=%d",a,b);
return 0;
}