Home > Blockchain >  In C, how to pass a variable number of arguments (say, 50 ) to a function which va_start() understan
In C, how to pass a variable number of arguments (say, 50 ) to a function which va_start() understan

Time:03-24

Question

Is there a way to pass many arguments to MyPrint() below using some kind of array containing a list of pointers to strings that va_start() understands before calling vsnprintf()?

Example of a format string specifier. It would be nice to create an array of the corresponding values and pass that to MyPrint() rather than individually passing each argument. I don't know if it's possible for va_start() to understand it. :(

"[0x%llX][%u] %s --- A=%llu (0x%llX)  B=%llu (0x%llX)  C=%llu (0x%llX)  X=%llu (0x%llX)  Y=%llu (0x%llX)  Z=%llu (0x%llX)"

Details

MyPrint() calls vsnprintf() which prints a formatted list of arguments to a character array. The declaration for vsnprintf() is shown below:

int vsnprintf(char *arr, size_t len, const wchar_t *format, va_list args);

Parameters

  • arr: Pointer to the character array where output is to be printed
  • len: Maximum number of characters that can be written to the array
  • format: Format in which the output will be printed
  • args: Pointer to the list of arguments to be printed

Demo

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

int MyPrint(char* buffer, int bufferSize, const char *format, ...)
{
    int len = 0;
    va_list arguments;
    va_start(arguments, format);
    len = vsnprintf(buffer, bufferSize, format, arguments);
    va_end(arguments);
    return len;
}

int main()
{
    char buffer[256];
    MyPrint(buffer, 256, "%s %s","Hello","World");
    printf("%s",buffer);
    return 0;
}

CodePudding user response:

Is there a way to pass many arguments to MyPrint() below using some kind of array containing a list of pointers to strings that va_start() understands before calling vsnprintf()?

The only defined ways to initialize a va_list, such as vsnprintf() requires as a parameter, are

  • via the va_start() macro, operating in the context of a variadic function to form a va_list from the function's variadic arguments, and

  • via the va_copy() macro, to make a copy of another va_list.

There is no mechanism in standard C to form a va_list from the elements of an array, except by passing them all, individually, to a variadic function.

Variadic functions are about coding flexibility, not data flexibility. If you want a function that handles arrays of data, then write a (non-variadic) one that does so.

Whenever you consider writing your own varargs function, smack yourself in the head and repeat the mantra: "varargs is not the answer". Only if you still have varargs in your head after a few iterations of that should you should consider actually investigating that option.

  • Related