C函数中的变量参数 [英] Variable arguments in C functions
问题描述
我已经阅读了有关变量参数函数"int func(int, ...)
"的信息.
这些函数的参数在哪里分配(堆栈或堆)?
I've read about variable arguments functions "int func(int, ...)
".
Where do the arguments of these functions get allocated (stack or heap)?
因为我读到va_end()
宏释放了分配给va_list
的空间,所以"frees"一词引起了我的注意.
Because I read that the va_end()
macro frees space assigned to va_list
, so that word "frees" caught my eyes.
注意:我知道常规函数会进入堆栈,但是这种类型的函数很有趣,因为参数的数量未知.
Note: I know that regular functions go to stack, but this type of function is interesting as the number of arguments is not known.
我只想确定这不像没有预定义空间的数组;
我们在最后使用malloc()
和free()
.
I just want to know for sure that it's not like arrays with no pre-defined space;
we use malloc()
and free()
at the end.
链接: https://www.tutorialspoint.com/cprogramming/c_variable_arguments.htm
推荐答案
c 本身未指定堆"或堆栈"之类的内容,因此对标准和可移植的 c 标准:静态,自动和动态存储.
c itself doesn't specify things like "heap" or "stack", so programming standard and portable c, you should better think in categories of the c standard: static, automatic and dynamic storage.
尽管如此,在典型的实现中,自动存储"转换为用于堆栈的堆栈".函数参数就是这种情况,可变参数函数也不例外.
Nevertheless, in a typical implementation, "automatic storage" translates to "the stack is used for it". This is the case for function arguments and variadic functions are no exception here.
va_end()
可能释放一些动态存储(通常是:分配在堆上)的原因是va_arg()
宏通常需要一些上下文信息来找到 next 参数. va_start()
将为该信息分配内存(而不是为参数本身分配内存),并以某种方式对其进行初始化,以使第一个va_arg()
调用返回第一个可变参数.
The reason va_end()
might free some dynamic storage (typically: allocated on the heap) is that the va_arg()
macro typically needs some context information to find the next argument. va_start()
will allocate the memory for that information (not for the arguments themselves) and initialize it in a way so that the first va_arg()
call returns the first variadic argument.
请注意,va_start()
的实现没有必须分配内存. va_list
的定义方式可以为所需的上下文信息提供空间.但是作为程序员,您应该完全没有兴趣,所有va_*
内容对您来说都是黑匣子,并且如果文档中注明致电
Note that an implementation of va_start()
doesn't have to allocate memory. va_list
might be defined in a way that it provides the space for the required context information. But that should be of no interest at all to you as the programmer, all the va_*
stuff is a black box for you and if the documentation states "call va_end()
when done for cleanup", you just do it ;)
这篇关于C函数中的变量参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!