The standard states:
Unless both pointers point to elements of the same array object or one past the last element of the array object, the behavior is undefined.
Why is it valid to reference one past the last element?
The standard states:
Unless both pointers point to elements of the same array object or one past the last element of the array object, the behavior is undefined.
Why is it valid to reference one past the last element?
It's okay to compute that pointer and compare to it only. The reason being that it can be used to pass and iterate over and array using a pair of pointers.
If it was not allowed by the standard, the following loop would have exhibited undefined behavior by the mere existence of pend
int arr[100] = {0};
for (int *pbegin = arr, *pend = arr + 100; pbegin != pend; ++pbegin)
{
// do stuff
}
This is especially important in C++, where the idiom of passing a range as "an iterator to the beginning and one-past the end" is used heavily by the standard library.