Reputation: 387
I am writing a function, that takes a variadic argument list and produces a formated string from those. The problem is, that i use sprintf to create the string and i need to explicity list all paramaters, while programming
sprintf(string, format, a0, a1, a2, ...);
On cppreference however the description of sprintf says, that ...
... (additional arguments) Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n).
What i understand like, that i can store all the data to a pointer location and hand the pointer to sprintf.
int arr[X];
arr[0] = a0;
...
sprintf(string, format, &arr);
Trying that resulted in an unexpected behavior. Only numbers were written to the string.
Does it actually work that way and is there maybe a better solution?
My first attempt was to add each variadic argument separatly to the string, but that produced a lot of calls to sprintf, what i want to avoid.
Is it possible to pass the variadic argument list from one function to another?
Upvotes: 0
Views: 477
Reputation: 387
Okay ... why did i not find this sooner...
The solution for me was to use vsnprintf
instead of sprintf
. That way one can pass the va_list to a formated string function and it is secure.
How to pass variable number of arguments to printf/sprintf
Upvotes: 2