Suppose I have two pointers to type T
:
T* first = ...// whatever
T* second = ... //whatever else
Can I be sure that the distance between those two pointers can never exceed:
((size_t)(-1))/sizeof(T)
?
When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed to. If two pointers to object types both point to the same object, or both point one past the last element of the same array object, they compare equal.
We already know that a pointer points to a location in memory and thus used to store the address of variables. So, when we define a pointer to pointer. The first pointer is used to store the address of the variable. And the second pointer is used to store the address of the first pointer.
Pointers are arguably the most difficult feature of C to understand. But, they are one of the features which make C an excellent language. In this article, we will go from the very basics of pointers to their usage with arrays, functions, and structure.
Pointers are used extensively in both C and C++ for three main purposes: to allocate new objects on the heap, to pass functions to other functions. to iterate over elements in arrays or other data structures.
You can only compute the distance between two pointers (subtract one pointer from another) if both pointers point to elements in the same array, or to one-past-the-end of the same array.
If the two pointers meet that constraint, then yes, the absolute value of the difference between the two pointers cannot exceed ((size_t)(-1)) / sizeof(T)
because size_t
must be wide enough to represent the size of any object in bytes.
If the two pointers do not meet that constraint, then there's no guarantee at all.
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