c 使用 va_list 打印参数列表
我有一个简单的参数列表。我只想将其打印到标准输出,但在打印“end”之前我得到了有线输出。有谁知道那个空行和不可读的字符来自哪里?
输出:
start
hello
hello2
hello3
hello 4
UH��AWAVAUATE1�S1�H��HH�E�
end
void printTest(const char* msg, ...) {
va_list ap;
int i;
const char* curMsg=0;
va_start(ap, msg);
printf("start\n");
for(curMsg= msg ; curMsg!=0 ; curMsg = va_arg(ap, const char*)){
printf("%s\n", curMsg);
}
printf("end\n");
va_end(ap);
}
int main(){
printTest("hello", "hello2", "hello3", "hello 4");
return 0;
}
I have a simple argument list. And I just wanna print it to stdout, but I'm getting wired output before printing "end". Does anyone know where that empty line and unreadable characters come from??
output:
start
hello
hello2
hello3
hello 4
UH��AWAVAUATE1�S1�H��HH�E�
end
void printTest(const char* msg, ...) {
va_list ap;
int i;
const char* curMsg=0;
va_start(ap, msg);
printf("start\n");
for(curMsg= msg ; curMsg!=0 ; curMsg = va_arg(ap, const char*)){
printf("%s\n", curMsg);
}
printf("end\n");
va_end(ap);
}
int main(){
printTest("hello", "hello2", "hello3", "hello 4");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您不传递空指针时,您如何期望读取空指针来终止循环?将调用更改为:
How do you expect to read a null pointer to terminate the loop when you're not passing one? Change the call to:
va_list 列表不是以 NULL 结尾的。事实上,它没有提供有关有多少参数的任何信息。你的论点必须提供一些关于有多少论点的指示。例如,对于 printf(),格式参数指示要处理的附加参数的数量。
如果需要列表以 NULL 结尾,则需要传递 NULL 作为最后一个参数。
The va_list list is not NULL-terminated. In fact, it doesn't provide any information about how many arguments there are. Your arguments must provide some indication of how many arguments there are. For example, with printf(), the format argument indicates the number of additional arguments to process.
If you need the list to be NULL-terminated, you'll need to pass NULL as the last argument.