c++ - Pointer Subtraction and an Alternative -


when working arrays, standard algorithms (in both c , c++) return pointers elements. convenient have index of element, perhaps index array, , subtracting beginning of array pointer:

int arr[100]; int *addressicareabout = f(arr, 100); size_t index = addressicareabout - arr; 

this seemed simple , effective enough. however, pointed out me pointer subtraction returns ptrdiff_t , that, in principle, there problems if "index" doesn't fit in ptrdiff_t. didn't believe implementation perverse enough allow 1 create such large arr (and thereby cause such issues), accepted answer here admits that's possible , i've found no evidence suggest otherwise. i've therefore resigned myself being case (unless can convince me otherwise) , careful going forward. answer proposes convoluted method of "safely" getting index; there nothing better?

that said, i'm confused possible workaround in c++. there have std::distance, std::distance(arr, addressicareabout) guaranteed well-defined? on 1 hand, (the pointer first element of) arr can incremented reach addressicareabout (right?), on other hand std::distance should return ptrdiff_t. iterators standard containers can (presumably) have same issues.

it extremely unlikely ever have 2 pointers same array difference doesn't fit ptrdiff_t.

on 64 bit implementations, ptrdiff_t signed 64 bit, you'd need array of 8 billion gigabytes. on 32 bit implementations, total address space limited 3 gb, 3 1/4 gb if lucky (it's address space, not ram, counts), you'd need array of more 2 gb doesn't leave else. , quite possible malloc refuse allocate array of size in first place. judgement of course.

while std::distance has advantages, suspect has same theoretical problem ptrdiff_t, since distances can positive , negative, , it's not 64 bit type on 32 bit implementation.

note if can allocate 3 gb array on 32 bit implementation, , have 2 int* first , last element of array, wouldn't surprised if pointer difference calculated incorrectly though result fits ptrdiff_t.


Comments