简体   繁体   中英

Unknown chars in va_list?

#include <stdio.h>
#include <stdarg.h>

void s(const char* param, ...)
{
    va_list arguments;
    va_start (arguments, param);
    const char* param_now = va_arg(arguments, const char*);

    while(param_now != NULL)
    {
        printf("%s", param_now);
        param_now = va_arg(arguments, const char*);
    }

    va_end (arguments);
}

int main()
{
    s("one", "two");
    return 0;
}

Why my code above doesn't work and displays unknown symbols instead of one and two?

Edit : found a pretty smart way to avoid including NULL at the end:

void add_s(const char* param, ...)
{
    return s(param, NULL);
}

You never terminated your sequence with a NULL parameter, what your while loop is checking for.

s("one", "two" , NULL );

Now only "two" appears. That is beacuse the first string is in parameter param . So you have to first print it, and then print all the optional parameters.

You can use a macro to avoid writing the NULL terminator. Something like:

#define my_s( ... )    s( __VA_ARGS__ , NULL )

Note that this requires at least one argument in my_s . ( and think about avoiding using macros in serious code )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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