Use snprintf
:
// value is int;
// buf is char *;
// length is space available in buf
snprintf(buf, length, "%d", value)
snprintf
has the advantage of being standard and giving your more flexibility over the formatting as well as being safe.
You could also use itoa
but be warned that it is not part of the standard. Most implementations have it though.
Usage:
// value is int;
// buf is char *;
itoa(value, buf, 10);
An interesting question is: how much space do you allocate for buf
? We note the following. With sizeof(int)
bytes per int
and eight bits per byte, the maximum value is approximately 2^(CHAR_BIT * sizeof(int) - 1)
(-1
is for sign bit). Therefore we need space to hold
floor(log_10(2^(CHAR_BIT * sizeof(int) - 1)) + 1
digits. But don't forget the sign and null terminator! So the maximum length of an integer representable here is
floor(log_10(2^(CHAR_BIT * sizeof(int) - 1)) + 3.
Of course, this could be wasting space if our values are small. To find out how much space a specific value needs:
floor(log_10(abs(value))) + 1 + (value < 0 ? 1 : 0) + 1