1 函数形参改变实参的值
#include <stdio.h>
void swap1(int x, int y)
{
int tmp;
tmp = x;
x = y;
y = tmp;
printf("x=%d, y=%d\n", x, y);
}
void swap2(int *x, int *y)
{
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
}
int main()
{
int a = 3;
int b = 5;
swap1(a, b); // 值传递
printf("a = %d, b = %d\n", a, b);
a = 3;
b = 5;
swap2(&a, &b); // 地址传递
printf("a2 = %d, b2=%d\n", a, b);
return 0;
}
输出结果:
tao@Taoc:~/Desktop/C/7$ ./7.5.1
x=5, y=3
a = 3, b = 5
a2 = 5, b2=3
2 数组名做函数参数
数组名做函数参数,函数的形参会退化为指针:
#include <stdio.h>
void printArrary(int *a, int n)
{
int i = 0;
for (i = 0; i < n; i++)
{
printf("%d, ", a[i]);
}
printf("\n");
}
int main()
{
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int n = sizeof(a) / sizeof(a[0]);
//数组名做函数参数
printArrary(a, n);
return 0;
}
输出结果:
1, 2, 3, 4, 5, 6, 7, 8, 9,
3 指针做为函数的返回值
#include <stdio.h>
int a = 10;
int *getA()
{
return &a;
}
int main()
{
*(getA()) = 111;
printf("a = %d\n", a);
// 输出: a = 111;
return 0;
}