Why my itoa implementation works only for 3 digit numbers?

2k views Asked by At

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;
}
2

There are 2 answers

0
Julian On BEST ANSWER

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 an int (you'll have to change the size of the initial memory allocation to account for the increase in possible digits).

#include <stdio.h>
#include <stdlib.h>

char* buildNumber(int n)
{
    int count = 0;
    char* v = calloc(11, sizeof(char));

    for (int i = n; i > 0; i /= 10) {
        v[++count] = i % 10 + '0';
    }

    v[0] = count + '0';
    return realloc(v, count + 1);
}

int main()
{
    char* v = buildNumber(1800);
    printf("%s", v); /* Prints 40081 */
    free(v);
}
2
i486 On

Possible solution:

char * _my_itoa( int i )
{
    static char res[11]; // buffer for max 4G value
    char * p = res + sizeof res - 1; // pointer to end of buffer
    *p-- = 0; // 0 - end of string
    while ( i > 0 )
    {
      *p-- = (char)( ( i % 10 ) + '0' );
      i /= 10;
    }
    return p;
}