Is there a way to figure out where in an array a pointer is?
Lets say we have done this:
int nNums[10] = {'11','51','23', ... }; // Some random sequence
int* pInt = &nNums[4]; // Some index in the sequence.
...
pInt++; // Assuming we have lost track of the index by this stage.
...
Is there a way to determine what element index in the array pInt is ‘pointing’ to without walking the array again?
Yes:
When pointers to elements of an array are subtracted, it is the same as subtracting the subscripts.
The type
ptrdiff_tis defined in<stddef.h>(in C++ it should bestd::ptrdiff_tand<cstddef>should be used).