I'm new to C.
I'm looking for an example where I could call a function to convert int
to string. I found itoa
but this is not part of standard C.
I also found sprintf(str, "%d", aInt);
but the problem is that I don't know the size of the required str. Hence, how could I pass the right size for the output string
There are optimal ways ways to appropriately size the array to account for variations in sizeof(int)
, but multiplying by 4 is sufficient for base 10. +1 is needed for the edge case of sizeof(int)==1
.
int x; // assign a value to x
char buffer[sizeof(int) * 4 + 1];
sprintf(buffer, "%d", x);
If you need to return the pointer to the string from the function, you should allocate the buffer instead of using stack memory:
char* integer_to_string(int x)
{
char* buffer = malloc(sizeof(char) * sizeof(int) * 4 + 1);
if (buffer)
{
sprintf(buffer, "%d", x);
}
return buffer; // caller is expected to invoke free() on this buffer to release memory
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With