1
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
3
  • 3
    Count the number of bytes your strings need again. Commented Sep 27, 2021 at 17:24
  • 2
    A string is by definition a sequence of non-zero chars, terminated by a char with value zero. For an array to hold such a sequence, it needs space for the terminating zero. If there is no zero, it is not a string, and treating it like a string makes no sense. Commented Sep 27, 2021 at 17:26
  • 1
    Unless you intend to modify those strings, the safest way to declare the array is char *s[] = { "one", "two", "etc..." }; That way you don't need to think about how long the strings are, or even how many are in the array. If you need to know the number of strings in the array, use size_t count = sizeof(s) / sizeof(s[0]); Commented Sep 27, 2021 at 18:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.