12

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

Tony Stark
  • 24,588
  • 41
  • 96
  • 113

1 Answers1

17
ptrdiff_t index = pointer_found - array_name;
Khaled Alshaya
  • 94,250
  • 39
  • 176
  • 234
  • 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 – Tony Stark Apr 26 '10 at 07:18
  • 2
    There is no array of type `void`, but there is a pointer of type `void`. – Khaled Alshaya Apr 26 '10 at 07:19
  • 1
    @hatorade cast the pointer to the type of the array elements. For example: `int arr[..]; void* p = &arr[1]; size_t index = (int*)p - arr;` – Khaled Alshaya Apr 26 '10 at 07:20
  • 2
    why do you use `size_t` and not `ptrdiff_t`? – jfs Apr 26 '10 at 07:27