In the textbook "Modern C" by Jens Gustedt, I read for pointers that "A pointer must point to a valid object or one position beyond a valid object or be null.". Why is pointing to one position beyond a valid object acceptable? E.g.:
int array[5] = {0};
int* p = array;
p = array + 5 // points to a valid location
p = array + 6 // points to an invalid location
it is possible for a pointer to an object and a pointer one past the end of a different object to hold the same address.
Using pointer arithmetic ++ as an iterator: Incrementing pointers with ++, and decrementing with -- is useful when iterating over each element in an array of elements. It is cleaner than using a separate variable used to keep track of the offset.
Supporting “one beyond the last” makes working with arrays simpler. For example, if a function is called with a pointer Start
to some element, it might want to prepare an end pointer End
and use a loop such as:
for (ElementType *p = Start; p < End; ++p)
To do this, End
must be a valid pointer.
We might consider instead setting End
to be the last element to be processed, rather than one beyond it, and using:
for (ElementType *p = Start; p <= End; ++p)
However, note that, after the final element is processed, p
will be incremented to beyond End
. Then, in order for p <= End
to be a valid expression, p
must be a valid pointer. So, we need to be able to do address arithmetic up to one beyond the last element of an array.
Your code comments express a probable misunderstanding. With ...
int array[5] = {0}; int* p = array; p = array + 5 // points to a valid location
... p
does not point to a valid location. It is allowed and well defined to evaluate array + 5
, and that produces a value that p
can store, but undefined behavior results from any attempt to dereference that pointer value.
Such a value for p
is sometimes useful as an exclusive upper bound on the addresses of elements of array
, or for indexing array
backwards (with strictly negative indexes), but you may not attempt to access a value through that value itself.
In contrast, in this case ...
p = array + 6 // points to an invalid location
... p
does not point to anything, at least inasmuch as can be determined by analysis of the code. Attempting to evaluate the expression array + 6
produces undefined behavior, and in particular, the result is not well defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With