No, an array of size 2
is not meant to store 3 elements, it can only store 2 elements. C does not prevent you from trying to access arrays beyond their boundaries, but the code then invokes undefined behavior.
The compiler should be smart enough to detect your erroneously accessing a[2]
, a[3]
and a[4]
. Maybe you did not give it enough of a warning level or maybe changing the optimization settings can do it. In any case, your code invokes undefined behavior, so anything can happen.
Here is a corrected version:
#include <stdio.h>
int main() {
int a[5];
a[0] = 1;
a[1] = 2;
a[2] = 3;
a[3] = 9;
a[4] = 99;
printf("%d\n", a[0]);
printf("%d\n", a[1]);
printf("%d\n", a[2]);
printf("%d\n", a[3]);
printf("%d\n", a[4]);
return 0;
}