Home > Mobile >  Why does the function not execute a specific line
Why does the function not execute a specific line

Time:12-14

I am trying to build a function that takes a positive integer number and represents it in a string using recursion. The string isn't initialized.

void intToStr(int num, char s[]){

    if (num / 10 == 0) {
        s[0] = num   '0';
        s[1] = '\0';
    }
    else {
        intToStr(num / 10, s);
        s[strlen(s)] = num % 10   '0';
        s[strlen(s)   1] = '\0';
    }
}

But I don't understand why when I run the code it skips this line

s[strlen(s) 1] = '\0';

CodePudding user response:

In:

        s[strlen(s)] = num % 10   '0';
        s[strlen(s)   1] = '\0';

strlen does not stay the same when the first line is executed. That first line puts a new character over the null that is terminating the string. Then the strlen(s) in the second line recalculates the string length. Since the null character is gone, strlen continues looking for a null character. What length it returns depends on whether there is another null character in the buffer already. If you did not initialize it, strlen could return some longer length, or the program could crash or otherwise misbehave.

You could solve this with:

        size_t length = strlen(s);
        s[length] = num % 10   '0';
        s[length   1] = '\0';

It might also be convenient to have intToStr return the length so it does not have to be recalculated each time:

size_t intToStr(int num, char s[])
{
    if (num / 10 == 0)
    {
        s[0] = num   '0';
        s[1] = '\0';
        return 1;
    }
    else
    {
        size_t length = intToStr(num / 10, s);
        s[length] = num % 10   '0';
        s[length 1] = '\0';
        return length 1;
    }
}
  • Related