简体   繁体   English

va_list 和 va_arg

[英]va_list and va_arg

I using va_list like this:我像这样使用 va_list:

void foo(const char* firstArg, ...) {
    va_list args;
    va_start (args, firstArg);
    for (const char* arg = firstArg; arg != NULL; arg = va_arg(arg, const char*)) {
         // do something with arg
    }

    va_end(args);
}

foo("123", "234", "345") foo("123", "234", "345")

the first three arguments was passed to foo correctly, but where "345" is done,前三个参数被正确传递给 foo,但在“345”完成的地方,

 arg = va_arg(arg, const char*) 

set some other freak value to arg .将其他一些怪胎值设置为arg

so What's the problem.所以有什么问题。 I using llvm3.0 as my compiler.我使用 llvm3.0 作为我的编译器。

C does not automatically put a NULL at the end of a ... argument list. C 不会自动将NULL放在...参数列表的末尾。 If you want to use NULL to detect the end of the arguments, you must pass it explicitly.如果要使用NULL来检测参数的结尾,则必须显式传递它。 Some functions (such as printf ) use earlier parameters to decide when they have reached the end of the arguments.某些函数(例如printf )使用较早的参数来决定何时到达参数的末尾。

( Edit : And actually if you want to put a NULL at the end, you need to cast it to the appropriate type so that it gets passed as the correct type of null pointer.) 编辑:实际上,如果您想在末尾放置一个NULL ,则需要将其强制转换为适当的类型,以便将其作为正确类型的空指针传递。)

I think the loop should be as follows:我认为循环应该如下:

for (const char* arg = firstArg; arg != NULL; arg = va_arg(args, const char*))

The change is va_arg(args, const char*) instead of va_arg(arg/*<<==*/, const char*) .变化是va_arg(args, const char*)而不是va_arg(arg/*<<==*/, const char*)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM