Ankesh Ankesh - 1 year ago 62
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:

int main(){
char input[8];
printf("Enter the integer: ");
char ones[10][5]={"zero","one","two","three","four","five","six","seven","eight","nine"};
return 0;

Enter the integer: 3

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download