As to your original question, in most cases it is simpler to have the caller provide a buffer. Taking care of the whole domain, a simple implementation might be:
Code: Select all
void toString(int i, char *s) {
static_assert(-5 % 3 == -2, "Compiler uses symmetric modulo"); /* if this fails, the code below won't work. */
if (i < 0)
*s++ = '-';
else
i = -i;
int t = i;
do s++;
while (t /= 10);
*s = 0;
do *--s = '0' - i % 10;
while (i /= 10);
}
This always turns the argument negative, because while each positive int can be turned negative, the reverse is not true (INT_MIN cannot be turned positive on most systems). Then it is simply a matter of working with division in the negative numbers. I put an assert in to verify that symmetric modulo is used, but it is used by pretty much all implementations I have ever come across. The alternative would not be pretty. In the case of absolute modulo, you get the inverse of each digit except 0, and the divisions would raise the argument towards -1, unless the argument was 0 from the start.
Now, there are some obvious areas for improvement, still. The buffer is unbounded at the moment, so the caller needs some way of knowing how to allocate enough memory from the start. Or alternatively, the caller could provide a buffer size, but then you need to specify what happens when the buffer runs out. I shall leave that as exercise for the reader.