[英]Unknown chars in va_list?
#include <stdio.h>
#include <stdarg.h>
void s(const char* param, ...)
{
va_list arguments;
va_start (arguments, param);
const char* param_now = va_arg(arguments, const char*);
while(param_now != NULL)
{
printf("%s", param_now);
param_now = va_arg(arguments, const char*);
}
va_end (arguments);
}
int main()
{
s("one", "two");
return 0;
}
Why my code above doesn't work and displays unknown symbols instead of one and two? 为什么我上面的代码不起作用,并显示未知符号而不是一个和两个?
Edit : found a pretty smart way to avoid including NULL at the end: 编辑 :找到了一种非常聪明的方法来避免在结尾处包含NULL:
void add_s(const char* param, ...)
{
return s(param, NULL);
}
You never terminated your sequence with a NULL parameter, what your while loop is checking for. 您永远不会用NULL参数终止您的序列,而while循环正在检查该参数。
s("one", "two" , NULL );
Now only "two" appears. 现在只有“两个”出现。 That is beacuse the first string is in parameter
param
. 那是因为第一个字符串在参数
param
。 So you have to first print it, and then print all the optional parameters. 因此,您必须先打印它,然后再打印所有可选参数。
You can use a macro to avoid writing the NULL terminator. 您可以使用宏来避免编写NULL终止符。 Something like:
就像是:
#define my_s( ... ) s( __VA_ARGS__ , NULL )
Note that this requires at least one argument in my_s
. 注意,这需要在
my_s
中至少有一个参数。 ( and think about avoiding using macros in serious code ) (并考虑避免在严肃的代码中使用宏)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.