在这里,我找到了如何在C中使用varargs的示例.
#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;
}
Run Code Online (Sandbox Code Playgroud)
我只能在某种程度上理解这个例子.
我不清楚为什么使用它们va_start(ap, count);
.据我所知,通过这种方式我们将迭代器设置为它的第一个元素.但是为什么默认情况下它没有设置到开头?
我不清楚为什么我们需要count
作为一个论点.C不能自动确定参数的数量?
我不清楚为什么使用它们va_end(ap)
.它有什么变化?它是否将迭代器设置为列表的末尾?但它是不是通过循环设置到列表的末尾?而且,为什么我们需要它呢?我们不再使用ap
了; 我们为什么要改变它?