Ankesh Ankesh - 4 months ago 9
C Question

Why the output is "threefour" when the index of the array is 3 and “seveneightnine” when the index is 7?

The size of the array “ones” is 10 and each can have maximum 5 characters. Output of ones[3] is ”threefour”, the max characters can be 5, and the size of “three” in ones[3] is 5. Why it prints”threefour” for ones[3]?
The code is:

#include<stdio.h>
#include<string.h>
int main(){
char input[8];
printf("Enter the integer: ");
scanf("%c",input);
char ones[10][5]={"zero","one","two","three","four","five","six","seven","eight","nine"};
printf("%d\n",input[0]-'0');
puts(ones[3]);
return 0;
}


Output:
Enter the integer: 3
3
threefour

Answer

You invoked undefined behavior by having puts() access out-of-range. Each elements of ones have only 5 elements, so there will be no room to store a terminating null-charcter when you try to store "three" there. Allocate one more element (i.e. use ones[10][6]) to avoid that.