在这里,我找到了如何在 C 中使用可变参数的示例。
#include <stdarg.h>
double average(int count, ...)
{
va_list ap;
int j;
double tot = 0;
va_start(ap, count); //Requires the last fixed parameter (to get the address)
for(j=0; j<count; j++)
tot+=va_arg(ap, double); //Requires the type to cast to. Increments ap to the next argument.
va_end(ap);
return tot/count;
}
我只能在一定程度上理解这个例子。
我不清楚我们为什么使用
va_start(ap, count);
. 据我了解,通过这种方式,我们将迭代器设置为其第一个元素。但是为什么默认不设置为开头呢?我不清楚为什么我们需要给出
count
作为论据。C不能自动确定参数的数量吗?我不清楚我们为什么使用
va_end(ap)
. 它有什么变化?它是否将迭代器设置到列表的末尾?但是它不是被循环设置到列表的末尾吗?此外,我们为什么需要它?我们不再使用ap
;为什么我们要改变它?