I am currently studying arrays. I think that I understand how they work, i.e., how they are filled, how elements are accessed, etc.) However, I have run into an example in my text that doesn't make sense to me. I thought it might be a misprint, so I actually ran the code and got the same result as the book. Here is my problem:
1 2 3 4 5 6 7 8 9 10 11 12
|
#include <iostream>
using namespace std;
int main()
{
int data[4];
for (int i = 1; i <= 4; i++) // Fill all 4 places of array
data[i] = i;
for (int i = 1; i <= 6; i++) // Print 6 places -- error
cout << data[i] << endl;
return 0;
}
|
This code is supposed to demonstrate what happens when out-of-bounds array indices are accessed.
Here is the output when I run the code snippet:
1
2
3
4
2130567168 (out-of-bounds)
2686840 (out-of-bounds)
I was expecting the output to give 3 values and 3 out-of-bounds numbers such as:
1
2
3
23145 (out-of-bounds)
32145 (out-of-bounds)
5342 (out-of-bounds)
The way the first for loop is written, I would expect 1 to be input into data[1] which would be the second array position,
given that data[0] is the first position. Then, I would expect 2 to be input into data[2] and 3 to be input into data[3] (the last valid array position. Then, when the second for loop runs it would output values found in data[1], data[2] and data[3] and
that the next three output values would be whatever is sitting in the memory cells beyond the end of the array. Can someone
help me understand where I am missing this? Thank you in advance.