It is undefined behavior to access an index that is out of bounds for an array (or standard library container for that matter, as they are all implemented using a raw array):
int array[] = {1, 2, 3, 4, 5};
array[5] = 0; // Undefined behavior
It is allowed to have a pointer pointing to the end of the array (in this case array + 5
), you just can't dereference it, as it is not a valid element.
const int *end = array + 5; // Pointer to one past the last index
for (int *p = array; p != end; ++p)
// Do something with `p`
In general, you're not allowed to create an out-of-bounds pointer. A pointer must point to an element within the array, or one past the end.