函数实现两个数的交换

# include <stdio.h>
# include <stdlib.h>


void Swap1(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
void Swap2(int *px, int *py)
{
int temp;
temp = *px;
*px = *py;
*py = temp;
}
int main()
{
int a, b;
printf("请输入两个数字:\n");
scanf("%d%d", &a, &b);
Swap1 (a, b);
printf("a=%d b=%d\n", a, b);
Swap2(&a, &b);
printf("a=%d b=%d\n", a, b);
system("pause");
return 0;

}

观察发现形参实例化后其实相当于参数的一份临时拷贝;

所以这里要用到传址调用,这种方式可以将函数和函数外边的变量建立起真正的联系,也就是函数内部可以直接操作函数外部的变量。

猜你喜欢

转载自blog.csdn.net/zhangtianqiang1314/article/details/79796892
今日推荐