Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

va_list and va_arg

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.

like image 956
holsety Avatar asked Mar 30 '12 02:03

holsety


People also ask

What is the argument type of va_arg()?

The argument ap is the va_list ap initialized by va_start (). Each call to va_arg () modifies ap so that the next call returns the next argument. The argument type is a type name specified so that the type of a pointer to an object that has the specified type can be obtained simply by adding a * to type .

What is the va_arg() macro?

The va_arg () macro expands to an expression that has the type and value of the next argument in the call. The argument ap is the va_list ap initialized by va_start (). Each call to va_arg () modifies ap so that the next call returns the next argument.

What is the syntax for va_arg function in C?

The syntax for the va_arg function in the C Language is: A variable argument list. The type of the argument. The va_arg function returns the value of the argument. In the C Language, the required header for the va_arg function is:

What is the value of the variable AP after va_start()?

If ap is passed to a function that uses va_arg (ap,type), then the value of ap is undefined after the return of that function. Each invocation of va_start () must be matched by a corresponding invocation of va_end () in the same function. After the call va_end (ap) the variable ap is undefined.


1 Answers

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

like image 101
Raymond Chen Avatar answered Dec 13 '22 04:12

Raymond Chen