Reputation: 21637
I am looking at some old code of mine that manipulates data buffers. I have many places that have:
char *ptr1 ;
char *ptr2 ;
And then I need to find the number of bytes between the two.
int distance = ptr2 - ptr1 ;
I am getting a lot of warnings about truncation. What is the type of
ptr2 - ptr1
I have found a number of answers dealing with pointer arithmetic but, oddly not an answer to this particular question.
Upvotes: 4
Views: 2140
Reputation: 504073
The result of subtracting two pointers† is a std::ptrdiff_t
. It is an implementation-defined signed integer; it could be larger than what an int
could store.
See http://en.cppreference.com/w/cpp/types/ptrdiff_t for more information.
†You can only subtract pointers if they point to elements of the same array, otherwise it's UB.
Upvotes: 8