Why my number to string converter keeps returning 000?

I have a issue with my number to string implemention. For some reason I keep getting 000 on my terminal even though. I couldn’t find a solution, what is the potantial issue here?
Im now sure my code is broken but don’t really see the problem.

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

/* public domain code feel free to use as what you wish, no warranties given*/
char finddigits(unsigned n) {
    char base = 6;
    unsigned tester = 100000;
    while(base % tester != 0) { 
        base--;
        /* inefficient but works for now */
        switch(tester) {
            case 100000:
                tester = 10000;
                break;
            case 10000:
                tester = 1000;
                break;
            case 1000:
                tester = 100;
                break;
            case 100:
                tester = 10;
                break;
            case 10:
                tester = 1;
                break;
        }
    }
    return base;
}

char* num2str(unsigned n) {
    char size = finddigits(n);
    char* tempbuf = malloc(size);
    *tempbuf = 48 + (n / pow(10, size));
    for(unsigned int i = 1; i < size; i++) 
        *(tempbuf + i) = 48 + (n % (10 * i));
    return tempbuf;
}

int main(int argc, char* argv[]) {
    int numbr = 210;
    printf("%s \n", num2str(numbr));
    /* expected 210 on string got 000 */
    return 0;
}

>Solution :

The computer does what you told it to do, which is to say, it does complete nonsense.

finddigits(210) returns 1, because 6 % 100000 isn’t 0 (it’s 6), 5%10000 isn’t 0 (it’s 5), 4 % 1000 isn’t 0 (it’s 4), 3 % 100 isn’t 0 (it’s 3), 2 % 10 isn’t 0 (it’s 2), but 1 % 1 is 0 so the loop stops and the function returns 1.

Then, num2str allocates 1 byte. In this 1 byte, it sets the first byte to 48 + (210 / 10) which is 69, ASCII code for the letter E. Since size is 1 the loop doesn’t run at all and num2str returns this allocation. When you print it, it prints the letter E – possibly with more gibberish after it since the string is not terminated, although for me it just printed E.

I have no idea how you managed to get 000.

You need to write code that tells the computer to do what you want it to do. When you can’t get it to do what you want it to, for one part of the code, don’t just skip that part of the code and go onto the next one. It all has to be right or it won’t work.

Leave a Reply