0

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?

Aeonos
  • 365
  • 1
  • 13
  • Not specifically a solution, but have you checked out parameter packs? – Malachi Mar 17 '17 at 06:55
  • working on a micro controller here without C++11 but thanks for your idea, i actually did not check out parameter packs – Aeonos Mar 17 '17 at 06:56
  • Right on. Another semi-side-note, I do a fair bit of microcontroller dev and C++ 11 *is* generally available. Are you sure it isn't for you? – Malachi Mar 17 '17 at 06:58
  • What cppreference is saying is that each of the arguments after the format string is either a value printf will read or a pointer printf will write. Each %n gets its own matching writeable pointer. – Cubbi Mar 17 '17 at 12:56

1 Answers1

2

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

Community
  • 1
  • 1
Aeonos
  • 365
  • 1
  • 13