Why does bidimensional char array behave this way in C?

68 Views Asked by At

Recently I came back to the C language and decided that HackerRank would be good to begin with. There is this problem : https://www.hackerrank.com/challenges/for-loop-in-c.

I tried this :

int main() 
{
    int a, b;
    scanf("%d\n%d", &a, &b);
    char rep[9][5] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

    for(int i = a; i <= b; i++)
    {
        if(i <= 9 && i >= 1)
        {
            printf("%s\n", rep[i - 1]);
        }
        else
        {
            printf((i % 2 == 0) ? "even\n" : "odd\n"); 
        }     
    }

    return 0;
}

and got this output:

eightnine
nine
even
odd

I know that the preffered way to do this is to use the const char * array, but shouldn't this work too? Why does it print an extra "nine"?

1

There are 1 best solutions below

0
Vlad from Moscow On BEST ANSWER

A string literal like that "three" contains 6 characaters including the terminating zero character '\0'.

So you need to declare the array rep at least like

char rep[9][6] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

Otherwise the conversion specifier %s used in this call of printf

printf("%s\n", rep[i - 1]);

will try to output all characters until the terminating zero character '\0' will be encountered.

Though it would be better to declare the array like

const char *rep[] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
size_t N = sizeof( rep ) / sizeof( *rep );

In the if statement of the for loop you can write

    if( 1 <= i && i <= N )

Pay attention to that in C++ the compiler will issue an error message because the declaration

char rep[9][5] = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};

is invalid in C++.

C++ does not allow to ignore the terminating zero character of string literals used as initializers of character aarrays.