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, the interesting bit is to figure out the size of the buffer for the array.
First, the number of digits in a number's decimal representation is ⌊log10n+1⌋. The maximum possible value of an unsigned integral type T can be represented in nbits = CHAR_BIT*sizeof(T) binary bits, which will need ⌊log102nbits⌋+1 decimal digits.
log102nbits = nbits×log102 = nbits×log(2)/log(10).
28/93 is a very good1 rational approximation of log(2)/log(10) (0.30107526881720431 vs 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 terminating 0. So we get:
#include <limits.h>
/* Figure out the maximum number of characters including the
terminating 0 to represent the numbers in integral type T */
#define SZ(T) (CHAR_BIT * sizeof(T) * 28 / 93 + 3)
So we can do:
char array[SZ(int)];
sprintf(array, "%d", n);
And we are sure that array has enough space. We don't have to worry about snprintf() or malloc()/realloc() and free() combination either.
Here is a complete program using the above:
#include <stdio.h>
#include <limits.h>
/* Figure out the maximum number of characters including the
terminating 0 to represent the numbers in integral type T */
#define SZ(T) (CHAR_BIT * sizeof(T) * 28 / 93 + 3)
#define PRINT(x) do \
{ \
printf("%s: %lu\n", #x, (unsigned long)SZ(x)); \
} while (0)
int main(void)
{
PRINT(int);
PRINT(long);
PRINT(size_t);
return 0;
}
1or good enough for this purpose.
char array[] = "2007";. If not, look atsprintf().