I'm trying to encapsulate sprintf
call in C function with variable number of arguments. The reason is that I want to have a log wrapper to send log via network in JSON format, instead of writing to console. And I don't want to call sprintf
before every log call, but rather pass format and arguments as in sprintf
function itself.
I followed this question How to pass variable number of arguments to printf/sprintf and I got string in format
parameter working correctly, but number arguments printed with %i
somehow printed wrong.
For example:
instead of 40
I get 1073546032
printed
instead of 0
I get 1073545776
printed
If I do sprintf
before calling my log function, I see correct numbers in the result string.
Here's my code, but it's exactly same as in other similar question:
void write_log(const char* format, ...)
{
char formatted_string[256];
va_list argptr;
va_start(argptr, format);
int len = sprintf(formatted_string, format, argptr);
va_end(argptr);
// formatted_string sent to JSON builder
}