Pointer subtraction or pointer comparison using <
, <=
, >
, or >=
has undefined behavior unless both pointers point to elements of the same array object, or just past the end of it. (For this purpose, a single object is treated as a single-element array.) The relational operators compare the array indices, and subtraction yields the difference in elements (&arr[5] - &arr[2] == 3
, for example).
It's likely to "work" (i.e., give you more or less consistent results) on most systems, though subtraction may still give nonsensical results if there are alignment problems.
You can convert any pointer-to-object value to intptr_t
or uintptr_t
(defined in <stdint.h>
) and back again without loss of information. Since intptr_t
and uintptr_t
are integer types, subtractions and comparisons on them are well defined -- but that doesn't mean that the comparison means anything with respect to the pointer values. And of course subtraction can overflow.
You can either live with the fact that your code's behavior is not defined by the standard (though it may happen to work on your system), or you can find a different way to solve your problem. For the latter, we might be able to help if you'll tell us what problem you're trying to solve.