#include <stdio.h>
//不能交换
void swap1(int a,int b){
//此处实质上是形参a和b值得交换,
//跟实参没有关系
int temp;
temp = a;
a = b;
b = temp;
}
//怎么交换正确的交换两个变量的值,不能交换
void swap2(int *p,int *p1){
//形参变量的地址进行的交换
int *temp;
temp = p;
p = p1;
p1 = temp;
}
//终级解决方案
void swap3(int *p,int *p1){
//通过指针直接修改变量的值了
int temp;
temp = *p;
*p = *p1;
*p1 = temp;
}
int main(int argc, const char * argv[]) {
int a = 4,b = 5; // a = 5,b = 4
printf("交换前:a = %d,b = %d\n",a,b);
swap3(&a, &b);
printf("交换后:a = %d,b = %d\n",a,b);
return 0;
}
|
|