用函数实现数的交换
#include<stdio.h>
void swap(int x,int y) //这个时候传递的就是值
{
int t;
t = x;
x = y;
y = t; //值交换
printf("a = %d
",x);
printf("b = %d
",y);
}
int main()
{
int a = 1,b = 2;
swap(a,b); //改变的是形参,但是实参没有改变
printf("a = %d
",a);
printf("b = %d
",b);
return 0;
}
得到结果:
#include<stdio.h>
void swap(int *x,int *y) //这个时候交换的是地址
{
int *t;
printf("a = %d
",x);
printf("b = %d
",y);
t = x;
x = y;
y = t;
printf("a = %d
",x);
printf("b = %d
",y); //前后的地址交换了
}
int main()
{
int a = 1,b = 2;
swap(&a,&b);
printf("a = %d
",a);
printf("b = %d
",b);
return 0;
}
#include<stdio.h>
void swap(int *x,int *y) //按指针传递
{
int t;
t = *x;
*x = *y;
*y = t; //此时交换的时指针指向的值
printf("a = %d
",*x);
printf("b = %d
",*y);
}
int main()
{
int a = 1,b = 2;
swap(&a,&b);
printf("a = %d
",a);
printf("b = %d
",b);
return 0;
}