Search code examples
cfor-loopmultidimensional-arrayprintfc-strings

Getting unexpected output for string array


a = 1;
b = 9;
char s[9][5]={"one","two","three","four","five","six","seven","eight","nine"};
for(int i=a;i<=b;i++)
{
  if(i<10)
     printf("%s\n",s[i-1]);
  else
    {
      if(i%2==1)
         printf("odd\n");
      else
         printf("even\n");
    }  
}

expected:

one
two
three
four
five
six
seven
eight
nine

got:

one
two
threefour
four
five
six
seveneightnine
eightnine
nine

Solution

  • Not all elements of this array

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

    contain a string. The type of elements is char[5]. So for example the string literal "three" is not completely contained in the third element of the array because there is no space to store the terminating zero character '\0' of the string literal and the conversion specifier %s is designed to output characters until the terminating zero character '\0' is encountered. This is the reason of the appearance of such an output like

    threefour
    seveneightnine
    eightnine
    

    So either you need to increase the size of elements of the array like

    char s[9][6]= { /*...*/ };
    

    or to use the following format string in the call of printf

    printf("%.*s\n", 5, s[i-1]);
    

    Pay attention to that this if statement

      if(i<10)
    

    does not make a great sense because i is always less than 10.