Re: convert int to C string
On Fri, 29 Jun 2012 06:04:02 -0700, Andrej Viktorovich wrote:
You can't return a pointer to a local array: the storage for the array
disappears at the end of the call.
You can't return a pointer to an *automatic* array (for that reason).
So only way is to create char[] in main method and pas it to function that
makes conversion from integer to string?
You can return a pointer to a static array, e.g.:
char* intToStr(int value)
{
static char buffer[33];
char* c = itoa(value,buffer,10);
return buffer;
}
but that isn't re-entrant, and you'll need to have finished using the
returned pointer before the next call to intToStr().
You can return a pointer to dynamically-allocated memory, e.g.:
char* intToStr(int value)
{
char* buffer = malloc(33);
char* c = itoa(value,buffer,10);
return buffer;
}
but then the caller has to explicitly free() the memory.
In C, having the caller pass in a suitably-sized buffer is usually the way
to go, so long as the caller can determine what is a suitable size without
too much effort.
In C++, you'd normally use a std::string rather than a char* (you can
then use the .c_str() method to get a char* for the data), e.g.:
std::string intToStr(int value)
{
std::ostringstream os;
os << value;
return out.str();
}