Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the restriction on distance between pointers of certain type in C++?

Tags:

c++

pointers

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)?

like image 546
sharptooth Avatar asked Oct 20 '11 06:10

sharptooth


People also ask

What is restriction on Pointer comparison?

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.

Why use pointers to pointers in C?

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.

Are pointers difficult?

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.

What are pointers used for?

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.


1 Answers

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.

like image 114
James McNellis Avatar answered Oct 04 '22 23:10

James McNellis