传值和传址:
看下面的代码(传值):
#include<stdio.h>
void swap (int x, int y);
void swap (int x, int y)
{
int t;
printf("In swap,互换前:x = %d, y = %d
", x, y);//x = 3,y = 5;
t = x;
x = y;
y = t;
printf("In swap,互换后:x = %d, y = %d
", x, y);//x = 5,y = 3;
}
int main ()
{
int x = 3, y = 5;
printf("In main,互换前:x = %d, y = %d
", x, y);//x = 3, y = 5;
swap(x, y);
printf("In main,互换后:x = %d, y = %d
", x, y);//x = 3, y = 5;
return 0;
}
运用指针之后(传址):
#include<stdio.h>
void swap (int *x, int *y);
void swap (int *x, int *y)
{
int t;
printf("In swap,互换前:x = %d, y = %d
", *x, *y);//x = 3,y = 5;
t = *x;
*x = *y;
*y = t;
printf("In swap,互换后:x = %d, y = %d
", *x, *y);//x = 5,y = 3;
int main ()
{
int x = 3, y = 5;
printf("In main,互换前:x = %d, y = %d
", x, y);//x = 3,y = 5;
swap(&x, &y);//注意这里是交换地址
printf("In main,互换后:x = %d, y = %d
", x, y);//x = 5, y = 3;
return 0;
}
函数无法改变实参的值不懂参考百度知道(实参和形参)
可变参数
#include<stdarg.h>
- va list
- va start
- va arg
- va end
代码:
#include<stdio.h>
#include<stdarg.h>////有很多宏,可以处理可变参数的函数
int sum (int n,...);//"..."代表占位符,未知数量 ,至少一个
int sum (int n,...)
{
int i, sum = 0;
va_list vap;//定义参数列表
va_start(vap, n);//初始化参数列表
for(i = 0;i < n;i++)
{
sum += va_arg(vap, int);//获取参数的值 ,参数的类型写清楚
}
va_end(vap);//关闭参数列表
return sum;
}
int main ()
{
int r;
r = sum(3, 1, 2, 3);
printf("r = %d
", r);
return 0;
}