Taha Paksu Taha Paksu - 1 month ago 19
C Question

c variadic functions, same arguments, different formats

I'm having a problem with

va_
methods, and I couldn't find an example (or didn't figure out what the keywords are). The problem is, I need to use the same args for different formats, but the compiler gives me:


incorrect usage of va_start


error. The code I'm trying is something like this:

void vSaveNecessaryFields(EnumA eFormat, ...)
{
va_list xArgs, xArgs2;
const char *fmt1 = NULL, *fmt2 = NULL;
char caString[100] = {0};

fmt1 = cpGetDbFormat(eFormat);
fmt2 = cpGetPrinterFormat(eFormat);

va_start(xArgs1, fmt1);
va_copy(xArgs2, xArgs1);
vsnprintf(caString, sizeof(caString), fmt1, xArgs1);

vSaveToDb(caString);

va_start(xArgs2, fmt2);
vsnprintf(caString, sizeof(caString), fmt2, xArgs2);
vPrintFormatted(caString);
va_end(xArgs2);
va_end(xArgs1);
}


How can I solve this problem?

Answer

The argument to va_start should be the eFormat argument. Furthermore, the va_list is declared as xArgs but you use xArgs1, which causes a syntax error.

void vSaveNecessaryFields(EnumA eFormat, ...) {
    va_list xArgs, xArgs2;
    const char *fmt1 = NULL, *fmt2 = NULL;
    char caString[100] = {0};

    fmt1 = cpGetDbFormat(eFormat);
    fmt2 = cpGetPrinterFormat(eFormat);

    va_start(xArgs, eFormat);
    vsnprintf(caString, sizeof(caString), fmt1, xArgs);
    va_end(xArgs);

    vSaveToDb(caString);

    va_start(xArgs2, eFormat);
    vsnprintf(caString, sizeof(caString), fmt2, xArgs2);
    vPrintFormatted(caString);
    va_end(xArgs2);
}
Comments