What happens when you try to set the value to the not existing element of an array in c++?


I made this code in c++ (I know that using using namespace should be avoided but it is a really short program):

using namespace std;
int main()
{   int tab[1];
    for(int i=0;i<7;i++)
    { cout<<"Give "<<i<<" element of the array: ";

With only 4 as an input it gives this output:

give 0 element of the array: 4 
give 1 element of the array: 4 
give 5 element of the array: 4 
give 6 element of the array: 4

and an error that according to Quora user Pavel Samsonov means: "0xC0000005 is a code for Access Violation error. It means that your program just tried to read, or write, in a section of memory that it has no access to."

With other numbers as an input it does other strange things.

What I am curious about is that why "i" variable suddenly changes it's value from 1 to 5. What happens when computer gets a code like this to execute?


0 Answers

Nobody has answered this question yet.

User contributions licensed under CC BY-SA 3.0