Goal: serialize data to JSON.
Issue: i cant know beforehand how many chars long the integer is.
i thought a good way to do this
You can call int len = snprintf(NULL, 0, "{data:%d}", 12312)
to test how much space you need.
snprintf
will print at most size
characters, where size
is the second argument, and return how many characters would have been necessary to print the whole thing, not counting the terminating '\0'
. Because you pass in 0, it won't actually write anything out (and thus will avoid any null pointer exception that would happen by trying to dereference NULL
), but it will still return the length that is needed to fit the whole output, which you can use to allocate your buffer.
At that point you can allocate and print to your buffer, remembering to include one more for the trailing '\0'
:
char *buf = malloc(len + 1);
snprintf(buf, len + 1, "{data:%d}", 12312);