As others have said, you should look at sprintf()
or snprintf()
. Assuming you are trying to convert an integral type T
to such an array, an interesting bit is to determine the buffer size for the array.
First, the number of digits in decimal notation with numbers is & llloor; log 10 n + 1 & rfloor ;. The maximum possible value of an unsigned integer type T
can be represented in binary bits nbits = CHAR_BIT*sizeof(T)
, which requires <log 10 2 nbits & rfloor; +1 decimal digits.
log 10 2 nbits = nbits x times; log 10 2 = nbits x times; log (2) / log (10).
28/93
- a very good rational approximation of 1 log(2)/log(10)
(0.30107526881720431 versus 0.30102999566398114).
So, using the above, we get our expression for the number of digits:
CHAR_BIT * sizeof(T) * 28 / 93 + 1
For signed numbers, we need to add 1 more for the -
sign, and we need to add 1 for the final 0
. So we get:
So we can do:
char array[SZ(int)]; sprintf(array, "%d", n);
And we are sure that array
has enough space. We do not need to worry about the combination of snprintf()
or malloc()
/ realloc()
and free()
.
Here is the complete program using the above:
#include <stdio.h>
1 or enough for this purpose.
Alok singhal
source share