-1

I'm trying to write an ITOA (integer to array) function using pointers.

So this is what I got so far. I debugged and it works just fine. The thing is, the printing itself doesn't work. I'm adding two screenshots.

Would appreciate some help.

int num_length(int number)
{
    int count = 0;

    while (number > 0)
    {
        count++;
        number /= 10;
    }

    return count;
}

void itoa(int number, char *strptr)
{
    int number_len = num_length(number);
    char *start = strptr;
    strptr += number_len - 1;

    while (strptr >= start)
    {
        *strptr = number % 10;
        number /= 10;
        strptr--;
    }
}

void print_string(char *strptr)
{
    while (*strptr != '\0')
    {
        printf("%c", *strptr);
        strptr++;
    }
}

void main(void)
{
    int number;
    char number_in_string[N] = { '\0' };
    char *strptr = &(number_in_string[0]);
    printf("Enter a number: ");
    scanf_s("%d", &number);

    itoa(number, strptr);

    print_string(number_in_string);
    getch();
}

Biffen
  • 6,249
  • 6
  • 28
  • 36

1 Answers1

2

If you're trying to get an array of numeric characters (as seems evident by your print_string(a) function), you'll need to adjust the values appropriately:

*strptr = number % 10 + '0';

As per your debugging output ('\x2', '\x5', '\x5') , you're correctly getting the individual digits of the number but those are binary values, not the character representations.

Turning the former into the latter involves adding '0' (0x30 if you're using ASCII, for example). C guarantees that the numeric values are contiguous so this is safe.


(a) ... which could, by the way, be replaced with a simple:

printf("%s", number_in_string);

in your main function.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953