So i tried below program with its expected output,
int main()
{
int x = 0;
int a[5];
int len = *(&a + 1) - a; //length of array
cout << "LEN:" << len << endl;
//len = 20;
for (int i = 0; i < len; i++) {
a[i] = i;
}
cout << "X :" << x << endl;
return 0;
}
Which gives expected output:
LEN:5
X :0
Then i uncommented line 8 (//len = 20;
) and tried again, which again gave the above correct output.
Then i commented line 8 and changed loop to for (int i = 0; i < 20; i++) {
, which gives below output,
LEN:5
X :6
I was expecting x
to be 0
since x
has nothing to do with the loop (or does it?), then i got this x
as 6
. Also it threw Segmentation fault
which is also expected in line 10 (accessing out of bound). Could anyone please explain what cause for this behavior? It was compiled with gcc
in windows environment.
(FYI: this is just an experimenting code)