Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to string in standard C

Tags:

c

I'm new to C.

I'm looking for an example where I could call a function to convert int to string. I found itoabut 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

like image 406
user836026 Avatar asked Feb 08 '23 09:02

user836026


1 Answers

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
}
like image 167
selbie Avatar answered Feb 15 '23 18:02

selbie