va_list and va_arg

帅比萌擦擦* 提交于 2020-01-13 03:52:47

问题


I using va_list like this:

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")

the first three arguments was passed to foo correctly, but where "345" is done,

 arg = va_arg(arg, const char*) 

set some other freak value to arg.

so What's the problem. I using llvm3.0 as my compiler.


回答1:


C does not automatically put a NULL at the end of a ... argument list. If you want to use NULL to detect the end of the arguments, you must pass it explicitly. Some functions (such as printf) use earlier parameters to decide when they have reached the end of the arguments.

(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.)




回答2:


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*).



来源:https://stackoverflow.com/questions/9936249/va-list-and-va-arg

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!