交换两个值函数swap()
刚开始学函数的时候就遇到过这个坑,突然想起就写一写,其实还是挺有趣的。
先讲下这个函数坑的地方,上代码
第一个坑
#include<stdio.h>
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int test1 = 10, test2 = 20;
swap1(test1, test2);
printf("%d %d\n", test1, test2);
return 0;
}
输出:
10 20
会发现test1的值和test2的值并没有交换
在函数里面改变的只是形参的值,当函数结束时,形参的生存期就结束了,其实并没有改变实参test1和test2当中的值
第二个坑
当我们学了指针之后就会想到可以用指针修改值
#include<stdio.h>
void swap(int *a, int *b)
{
int *temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int test1 = 10, test2 = 20;
swap1(&test1, &test2);
printf("%d %d\n", test1, test2);
return 0;
}
输出:
10 20
当然还是没有交换两个的值,这又是为什么呢?传入到swap函数中的是存放这两个数的地址。但是在函数当中并没有改变这些地址中指向的值,而是把地址交换了一遍,再把这些地址中存放的数输出时还是和之前是一样的
接下来就讲解2种方法来写swap函数
第一种用指针
#include<stdio.h>
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int test1 = 10, test2 = 20;
swap(&test1, &test2);
printf("%d %d\n", test1, test2);
return 0;
}
输出:
20 10
第二种用引用
#include<stdio.h>
void swap(int&a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int test1 = 10, test2 = 20;
swap(test1, test2);
printf("%d %d\n", test1, test2);
return 0;
}
输出:
20 10