title: How to return an index from a bsearch or lfind? - sort distorts return vals
body: <p>I've looked at this already and tried to implement, but it keeps giving me a seg fault to do it this way:
  <a href="https://stackoverflow.com/questions/16211667/determining-index-from-bsearch-and-lfind">Determining index from bsearch and lfind?</a> - here is the link for reference.</p>
  
  <p>Basically, I'm trying to figure out the index in an array from a pointer that is returned by either bsearch or lfind. </p>
  
  <pre><code>void *val;
  void *begin = (char *)v-&gt;elems (I need to use this separate variable)
  </code></pre>
  
  <p>Then, I call on either search, which seems to be working fine...</p>
  
  <pre><code>val = bsearch(key, begin, v-&gt;count, v-&gt;elemsz, cmp);
  </code></pre>
  
  <p>And based on the link above, I'm trying to do the following:</p>
  
  <pre><code>index = *(int*)((char*)value_to_find - (char*)start_ptr)/sizeof(cv-&gt;elemsz)
  </code></pre>
  
  <p>However it segfaults everytime I do this. My logic is that I cast both void pointers to type of char*, then subtract the distance b/w the pointers since you can't do pointer arithmetic on void. I divide this by the size of each element to return the index, which needs to be cast to an int. What am I missing here?</p>
  
  <p><strong>EDIT: Changing sizeof(cv->elemsz) to just elemsz did return the right indices. However, now the problem is that if the vector is sorted using qsort, it is returning the wrong value (index 10 when 20 is expected, etc).</strong></p>