C - how to convert a pointer in an array to an index?

Tony Stark picture Tony Stark · Apr 26, 2010 · Viewed 7.7k times · Source

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

Answer

AraK picture AraK · Apr 26, 2010
ptrdiff_t index = pointer_found - array_name;