It's undefined behavior as far as I know. Run a larger program with that and it will crash somewhere along the way. Bounds checking is not a part of raw arrays (or even std::vector).
Use std::vector with std::vector::iterator
's instead so you don't have to worry about it.
Edit:
Just for fun, run this and see how long until you crash:
int main()
{
int array[1];
for (int i = 0; i != 100000; i++)
{
array[i] = i;
}
return 0; //will be lucky to ever reach this
}
Edit2:
Don't run that.
Edit3:
OK, here is a quick lesson on arrays and their relationships with pointers:
When you use array indexing, you are really using a pointer in disguise (called a "reference"), that is automatically dereferenced. This is why instead of *(array[1]), array[1] automatically returns the value at that value.
When you have a pointer to an array, like this:
int array[5];
int *ptr = array;
Then the "array" in the second declaration is really decaying to a pointer to the first array. This is equivalent behavior to this:
int *ptr = &array[0];
When you try to access beyond what you allocated, you are really just using a pointer to other memory (which C++ won't complain about). Taking my example program above, that is equivalent to this:
int main()
{
int array[1];
int *ptr = array;
for (int i = 0; i != 100000; i++, ptr++)
{
*ptr = i;
}
return 0; //will be lucky to ever reach this
}
The compiler won't complain because in programming, you often have to communicate with other programs, especially the operating system. This is done with pointers quite a bit.