I thought that any number under 21 would result in an error but it does not. |
You mean, any number
over 21, right?
Here's an integer array with 21 elements:
int a[21];
I can access these elements with an index. The first element is at index location zero.
1 2
|
a[0] = 128;//whatever I want to do with it
std::cout << a[0] << std::endl;
|
Accessing an element that's not within the bounds of the array will result in undefined behavior.
1 2 3 4
|
int a[21];
for(unsigned short i=0; i<22; ++i) {//undefined behaviour
a[i] = 0;
}
|
At the end of that for loop, I'm attempting to access index location 21, which would be the 22nd element - which doesn't exist.
To be more specific, the memory that would belong to the 22nd element exists, but doesn't belong to the array. It belongs to something else, so by changing it, you evoke undefined behavior.
Arrays are "left over" from C, where there was no way to ensure bounds-checking. Now, C++ offers different ways of bounds-checking.
For instance, the STL vector container can access elements with or without bounds checking.