Reputation: 98
int test[3] = {1,2,3};
cout<<test[3]<<endl;
// this will get a error
but
int test[3] = {1,2,3};
int (*A)[3];
A = &test;
cout<<test[3]<<(*A)[3]<<endl;
// this will print -858993460 withiout any errors
So could anyone tell me why? i am really confused by that.
in the first case why it is not outofboundary error but an undefined error? and why the second case will not get a error? i used to think they are the same...
actually i did know the array start from 0, i am confused by why the first got an error but the second won't????
Upvotes: 0
Views: 123
Reputation: 47593
Array indices in C/C++ start from 0. Therefore an array of size 3, has valid indices 0, 1 and 2.
Right now, you have your variable test
on the program stack. Therefore, the memory outside the bound of the array is still yours (that is why you don't get a segmentation fault (access violation) error when you are reading index 3 of your array). However, you are reading part of the stack that is gibberish from your previous function calls, resident gibberish on the memory or other variables you have in the function. That is why you are getting weird numbers as a result.
You should beware of going out of array bounds. In a complicated program, that is really hard to debug, because you go over the stack changing other variables and all you see when debugging is random behavior in variables you didn't even touch!!
Upvotes: 2
Reputation: 88017
Undefined behaviour seems a very tricky concept for newbies to understand. But it's very simple, if you break the rules of C++ (as both your examples do) then, very often, the behaviour of your program is undefined. It means exactly what it says and it's pointless asking 'why does it do that' as there are no longer any rules or laws applicable to your situation.
Upvotes: 3
Reputation: 272772
You are invoking undefined behaviour. In both cases, you are indexing beyond the bounds of the array; the corresponding behaviour is undefined. It might crash, or it might output nonsense, or it might do something else.
Upvotes: 10