I have to to write an implementation of itoa
,
where the output representation is contained in an array, v
for example. The array format must be as follows:
v[0] - the length of number (in digits)
v[1] ... v[v[0]] - the number's digits, as chars in reversed order
Example:
n = 123 => v = ['3', '3', '2', '1']
Below is my itoa
implementation, but I can only get it to work for numbers containing exactly three digits. Could you point me in the right direction? What am I doing wrong or what am I missing? I have been trying to get this right for a couple of hours now.
char* build_number(int n)
{
int i = 1;
char *v = NULL;
v = (char*) calloc(1, sizeof(char));
while (n > 0)
{
v[i] = '0' + (n % 10);
n /= 10;
v = realloc(v, i);
i ++;
}
v[0] = '0' + (i - 1);
return v;
}
Assuming you're limited to using C and not C++, this should do the trick. You haven't specified whether or how you want to support negative values, so you'll want to consider that. If you don't intend on supporting negative values, your function should accept an
unsigned int
instead of anint
(you'll have to change the size of the initial memory allocation to account for the increase in possible digits).