> Why does this ouput random characters ?
Because you are returning a pointer to memory local to convert(), which when the function returns, will point to garbage. Always make sure that memory you want to use stays in scope as long as you need it, as it does in this program.
Code:
#include <limits.h>
#include <stdio.h>
/* Convert a number to string representation. Returns nonzero on failure; if the string was too
short, it returns the minimum space needed. */
int itostr (int value, char buff[], size_t size);
int main(void)
{
int value = 123;
char buff[5];
if ( itostr(value, buff, sizeof buff) == 0 )
printf("Value %d as a string: \"%s\"\n", value, buff);
getchar();
return 0;
}
int itostr (int value, char buff[], size_t size)
{
int result = 0;
result = snprintf(buff, size, "%d", value);
if (result >= size)
return result;
else
return !result;
}
$ ./a
Value 123 as a string: "123"