How is this array declaration in C possible?

Viewed 116
int arr[5]={1,2,3,4,5,6,7,8,9};

This way of declaration is not giving an error and the array is stored up till the 4th index, if I try to output arr[5] it will give garbage value. Can anyone explain how this way is possible?

Edit: I was trying to run the following code in an online compiler:

#include <stdio.h>
int main() {
    int arr[5]={1,2,3,4,5,6,7,8,9};
    int i;
    for(int i=0; i<6;i++){
        printf("arr[%d]=%d\n", i,arr[i]);
    }
    return 0;
}
1 Answers

It will initialize only 5 elements of the array. The remaining initializers will be ignored. The compiler will emit a diagnostic message (warning).

<source>:11:23: note: (near initialization for 'arr')
<source>:11:25: warning: excess elements in array initializer

This way of declaration is not giving an error and the array is stored up till the 4th index

This is correct - you need to read the warning messages and notes. Do not ignore warnings!!

if I try to output arr[5] it will give garbage value

You invoke Undefined Bahavour by reading outside the array bounds.

Related