Accessing an out-of-bounds index
suggest changeIt is undefined behavior to access an array outside its bounds. The same rule applies when using an unchecked subscript operation on a standard-library container, regardless of how that container is implemented:
int array[] = {1, 2, 3, 4, 5};
array[5] = 0; // Undefined behavior
It is allowed to form a pointer one past the end of the array (in this case array + 5), but you must not dereference it, because it does not point at a valid element.
const int* end = array + 5; // Points one past the last element
for (int* p = array; p != end; ++p) {
// Use *p.
}
In general, pointer arithmetic must produce a pointer to an element of the same array or one past its end. The one-past-the-end pointer can be compared or subtracted, but it must not be dereferenced.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents