错误代码如下:运行结束后a,b的值并没有像我预想的那样发生交换!
#include<stdio.h>
#include<stdlib.h>
void swap(int x, int y){
int tmp = 0;
tmp = x;
y = x;
y = tmp;
}
int main(){
int a = 1;
int b = 2;
swap(x, y);
printf("x=%d y=%d", a, b);
system("pause");
return 0;
}
改进如下:
swap1是交换前的值
swap是交换后的值
#include<stdio.h>
#include<stdlib.h>
void swap1(int x, int y){
int tmp = 0;
tmp = x;
y = x;
y = tmp;
}
//对指针解引用:拿着内存中的房间号,找到对应房间中的内容是啥)
void swap2(int *px, int *py){
int tmp = 0;
tmp = *px;
*px = *py;
*py = tmp;
}
int main(){
int a = 1;
int b = 2;
swap1(a, b);
printf("swap1::a=%d b=%d\n", a, b);
swap2(&a, &b);
printf("swap2::a=%d b=%d\n",a,b);
system("pause");
return 0;
}
总结如下:
在c语言中,形参是实参的一份副本(拷贝)
如果需要让函数内部能够影响到函数外部的变量,需要按照指针的方式来传参。