Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Implement Variadic function in C

I am trying to write wrapper for a log function with a printf-like behavior.

Can anyone tell me why the following example does not work?

#include <stdarg.h>

void message(int level, const char* format, ...)
{
    if(level > 3)
        return;

    static char msgBuff[1024] = {0};

    va_list argptr;
    va_start(argptr, format);
    snprintf(msgBuff, sizeof(msgBuff), format, argptr);
    va_end(argptr);
    printf("%s", msgBuff); // Dummy Call
}


int main()
{
    int a = 42;
    message(3, "This is a test: %s %i", "The answer is ", a);
    return 0;
}

Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is a test:  0

>Solution :

The arguments to snprintf after the format string must be the individual arguments expected according to the conversion specifiers in the format string. argptr is not such an argument, so the call is incorrect.

To print variable arguments using a va_list, call vsnprintf instead of snprintf.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading