views:

160

answers:

1

In the many search functions of C (bsearch comes to mind) if a result is found, a pointer to the spot in the array is returned. How can I convert this pointer to the index in the array that was searched (using pointer arithmetic, i assume).

+8  A: 
ptrdiff_t index = pointer_found - array_name;
AraK
and if the arrays are type void, i get a compile warning. so it doesn't know how to do the subtraction correctly. i ended up converting both to (char *), subtracting, then dividing by the size of an element. i'm not sure if that works, though
hatorade
There is no array of type `void`, but there is a pointer of type `void`.
AraK
@hatorade cast the pointer to the type of the array elements. For example: `int arr[..]; void* p = size_t index = (int*)p - arr;`
AraK
why do you use `size_t` and not `ptrdiff_t`?
J.F. Sebastian
@J.F. Sebastian I think you are correct. Changed.
AraK