相关疑难解决方法(0)

在C中使用varargs的一个例子

在这里,我找到了如何在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)

我只能在某种程度上理解这个例子.

  1. 我不清楚为什么使用它们va_start(ap, count);.据我所知,通过这种方式我们将迭代器设置为它的第一个元素.但是为什么默认情况下它没有设置到开头?

  2. 我不清楚为什么我们需要count作为一个论点.C不能自动确定参数的数量?

  3. 我不清楚为什么使用它们va_end(ap).它有什么变化?它是否将迭代器设置为列表的末尾?但它是不是通过循环设置到列表的末尾?而且,为什么我们需要它呢?我们不再使用ap了; 我们为什么要改变它?

c syntax variadic-functions

34
推荐指数
3
解决办法
4万
查看次数

标签 统计

c ×1

syntax ×1

variadic-functions ×1