#include <stdio.h>
main() {
int a[1];
a[0] = 1;
a[1] = 2;
a[2] = 6;
printf("%d\n", a[2]);
}
Although a
is array of size 1
, why does it accept a[2] = 6
?
#include <stdio.h>
main() {
int a[1];
a[0] = 1;
a[1] = 2;
a[2] = 6;
printf("%d\n", a[2]);
}
Although a
is array of size 1
, why does it accept a[2] = 6
?
Although a is array of size 1 then does it accepts a[2]=6?
You think it accepts because it invokes undefined behavior.
Arrays are 0 based indexing in C, and for an array with size 1, only arr[0]
is valid access, not even arr[1]
. Attempt to access any other index other than 0 in this case will cause out-of-bound access which invokes UB.
By default C spec does not provide any bound checking for array indexing, so you don;t get an error by default. However, if you enable compiler warnings, you should be able to get a hint, at least. FWIW, -Warray-bounds=1
with -O2
should warn you.
That said, for a general hosted environment, the signature of main()
is int main(void)
in case you don't want to use any command line arguments for the program.