+ 1
Why this code is working? , You can try on VSCode and online compiler
4 Answers
+ 3
Declaring array size just 5 but accessing it's beyond it's boundaries.. Error. or undefined behavior..
+ 1
Trying to access array elements beyond it's bounds is an Undefined behaviour in C/C++.
Because of this, a lot of implementations doesn't perform a check for this by default .
If your program tries to access an illegal memory location ( memory that doesn't belong to that program ), your operating system terminates the program by throwing a segmentation fault.
The only reason why this program might work in some cases is because your program has been allocated more memory.
+ 1
This question is answered, however i want say here that this code is perfectly fine. The error you get is not a C++ exception, but OS exception.
In reality if you try to run this code under other OS it may work. You get this exception because the most operating systems nowdays have limitations on what each application can access in system memory.
+ 1
c++ lets you access some values beyond your array. Why it is so is beyond me. It's like having no fence on the edge of a cliff. So it's proceed at your own risk.
https://www.geeksforgeeks.org/accessing-array-bounds-ccpp/
btw, your example should be:
(It thows an error in Sololearn if the items are more than 10, but values can be stored in undefined regions.)
#include <iostream>
using namespace std;
int main() {
int n=5;
int array[n]={12,57,45,8,6,86,8,6,8,42};
cout<<array[9];
return 0;
}