For starters according to the C Standard the function main
without parameters shall be declared like
int main( void )
that is its return type shall be int
.
Your program has undefined behavior because the returned pointer from the function int2str
points to a local array with the automatic storage duration that will not be alive after exiting the function. So the pointer will have an invalid value. The memory occupied by the local array can be overwritten by a call of any other function (for example by a call of printf
within main).
So you have to allocate dynamically memory for the destination string. To use a local array with static storage duration within the function is not a good idea because calling the function several times will lead that previous result strings will be overwritten.
Pay attention to that for example the value of INT_MIN
(the user of the function can pass any valid integer value) can be equal to -2147483648
that requires a character array of 12
elements to store the string that represents such a number.
To calculate the required size of the string you can use a call of the C function snprintf
with the second argument equal to 0
.
Here is a demonstrative program.
#include <stdio.h>
#include <stdlib.h>
char * int2str( int x )
{
int n = snprintf( NULL, 0, "%d", x );
char *s = malloc( n + 1 );
if ( s )
{
snprintf( s, n + 1, "%d", x );
}
return s;
}
int main(void)
{
char *s = int2str( 1001 );
if ( s ) puts( s );
free( s );
return 0;
}
Its output is
1001