问题
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