我如何通过 C90 中的函数传递 va_list
我想将 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
}
在我看来,我的 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);
}
I want to pass a va_list through to another function. Here is an example of what i am trying to do:
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
}
It seems to me that my va_list ap
is a char
pointer, how can i get the whole List? How can i rewrite my_printf()
to pass the whole or a fake va_list
to subfunctions? I can not modify my subfunctions to accept va_list
pointers, so i will have to modify my_printf
.
EDIT:
I realize that the following would work, however this is not what i want.
void my_printf_1(char* string, ...) {
va_list ap;
va_start (ap, string);
vprintf(string, ap);
va_end(ap);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你需要按照你所说的去做,但要明确。也就是说,传递实际的 va_list 对象。
请参阅
vsnprintf()
函数获取灵感。在标准库中,采用显式va_list
的函数通常以v
为前缀。va_list
没有可供您使用的内部结构,它是不透明的。您所能做的就是在You need to do what you say, but explicitly. That is, pass the actual
va_list
object.See the
vsnprintf()
function for inspiration. Functions that take an explicitva_list
are often prefixed with av
in the standard library.The
va_list
doesn't have an internal structure that you can work with, it's opaque. All you can do is defined in the<stdarg.h>
header.查看 vprintf 和朋友。 http://www.manpagez.com/man/3/vprintf/
Check out vprintf and friends. http://www.manpagez.com/man/3/vprintf/