When converting an integer to text, typically I create a big buffer to use with sprintf()
to hold any potential result.
char BigBuffer[50];
These are fine.
I designed the original snprintf()
function (in *BSD, that eventually made it into C99) to return the number of characters that would have been printed, had the buffer been large enough. If you have a conforming snprintf()
you can do the printing twice, with the first telling you how much space to allocate (you must add one for the terminating '\0'
of course). This has two obvious drawbacks: it has to do the formatting twice, and it introduces the possibility of synchronization issues, where the first call changes something (e.g., writing via %n
directive) so that the second call produces different output.
Unfortunately, there are non-compliant snprintf()
implementations where this does not work anyway. [Edit: it works for the usage in jxh's answer, where you supply a large buffer; the failing case is when you supply a too-small buffer to find out how much room you need.]