Joh*_*nes 1 c variadic-functions cvi c89
我想将va_list传递给另一个函数.这是我想要做的一个例子:
void my_printf_1(char* string, ...) {
va_list ap;
va_start(ap, string);
printf(string, ap);
va_end(ap);
}
void my_printf_2(char* string, ...) {
va_list ap;
va_start(ap, string);
printf(string, *ap);
va_end(ap);
}
int main(void) {
my_printf_1("Hello %i\n", 12); //Shows me the pointer
my_printf_1("Hello \n"); //Runtime Error - too many arguments
my_printf_2("Hello %i\n", 12); //Displays correctly because 12 < char
my_printf_2("Hello %i\n", 500); //Displays incorrectly because 500 > char
my_printf_2("Hello %i %i\n", 12, 12); //Displays 12, then crashes Runtime Error not enough arguments
my_printf_2("Hello \n"); //Runtime Error - too Many Arguments
}
Run Code Online (Sandbox Code Playgroud)
在我看来,我va_list ap
是一个char
指针,我怎么能得到整个列表?我如何重写my_printf()
以将整个或假的传递va_list
给子功能?我不能修改我的子函数来接受va_list
指针,所以我将不得不修改my_printf
.
编辑:我意识到以下可行,但这不是我想要的.
void my_printf_1(char* string, ...) {
va_list ap;
va_start (ap, string);
vprintf(string, ap);
va_end(ap);
}
Run Code Online (Sandbox Code Playgroud)
你需要做你说的,但要明确.也就是说,传递实际va_list
对象.
查看vsnprintf()
功能的灵感.显式的函数va_list
通常以v
标准库中的a为前缀.
在va_list
不具有内部结构,你可以工作,它是不透明的.你可以做的就是在<stdarg.h>
标题中定义.