在 C 中使用 varargs 的示例 [英] An example of use of varargs in C

查看:26
本文介绍了在 C 中使用 varargs 的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里我发现了一个如何在 C 中使用 varargs 的示例.

Here I found an example of how varargs can be used in 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;
}

我只能在一定程度上理解这个例子.

I can understand this example only to some extent.

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

  1. It is not clear to me why we use va_start(ap, count);. As far as I understand, in this way we set the iterator to its first element. But why it is not set to the beginning by default?

我不清楚为什么我们需要将 count 作为参数.C不能自动确定参数的数量吗?

It is not clear to me why we need to give count as an argument. Can't C automatically determine the number of the arguments?

我不清楚我们为什么使用 va_end(ap).它有什么变化?它是否将迭代器设置到列表的末尾?但是它不是被循环设置到列表的末尾吗?此外,我们为什么需要它?我们不再使用 ap;我们为什么要改变它?

It is not clear to me why we use va_end(ap). What does it change? Does it set the iterator to the end of the list? But is it not set to the end of the list by the loop? Moreover, why do we need it? We do not use ap anymore; why do we want to change it?

推荐答案

请记住,参数是在堆栈上传递的.va_start 函数包含用正确的堆栈指针初始化 va_list 的魔法"代码.它必须传递函数声明中最后一个命名的参数,否则它将不起作用.

Remember that arguments are passed on the stack. The va_start function contains the "magic" code to initialize the va_list with the correct stack pointer. It must be passed the last named argument in the function declaration or it will not work.

va_arg 所做的是使用这个保存的堆栈指针,并为提供的类型提取正确的字节数,然后修改 ap 使其指向下一个参数在堆栈上.

What va_arg does is use this saved stack pointer, and extract the correct amount of bytes for the type provided, and then modify ap so it points to the next argument on the stack.

实际上这些函数(va_startva_argva_end)实际上并不是函数,而是作为预处理器宏实现的.实际的实现还取决于编译器,因为不同的编译器可以有不同的堆栈布局以及它如何将参数压入堆栈.

In reality these functions (va_start, va_arg and va_end) are not actually functions, but implemented as preprocessor macros. The actual implementation also depends on the compiler, as different compilers can have different layout of the stack and how it pushes arguments on the stack.

这篇关于在 C 中使用 varargs 的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆