值传递和(地)址传递的区别
值传递
#include<stdio.h>
void swap(int a, int b)
{
int temp = a;
a = b;
b = temp;
}
int main(void)
{
int a = 10;
int b = 20;
printf("%d\n", a); //输出:10
printf("%d\n", b); //输出:20
//值传递 形参不影响实参的值
swap(a,b);
printf("%d\n", a); //输出:10
printf("%d\n", b); //输出:20
return 0;
}
程序原理解析如下:
(地)址传递
#include<stdio.h>
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main(void)
{
int a = 10;
int b = 20;
printf("%d\n", a); //输出:10
printf("%d\n", b); //输出:20
//(地)址传递 形参可以改变实参的值
swap(&a,&b);
printf("%d\n", a); //输出:20
printf("%d\n", b); //输出:10
return 0;
}
程序原理解析如下: