I've looked at this already and tried to implement, but it keeps giving me a seg fault to do it this way: Determining index from bsearch and lfind? - here is the link for reference.
Basically, I'm trying to figure out the index in an array from a pointer that is returned by either bsearch or lfind.
void *val;
void *begin = (char *)v->elems (I need to use this separate variable)
Then, I call on either search, which seems to be working fine...
val = bsearch(key, begin, v->count, v->elemsz, cmp);
And based on the link above, I'm trying to do the following:
index = *(int*)((char*)value_to_find - (char*)start_ptr)/sizeof(cv->elemsz)
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?
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).
The problem is that you are dividing the difference in addresses by the size of the elemsz
property, which is probably a 32-bit unsigned integer (in other words, sizeof
returns 4, regardless of your element size). Just divide by cv->elemsz
instead.
index = *(int*)((char*)value_to_find - (char*)start_ptr)/cv->elemsz;
Also, you need to do similar arithmetic to utilize the returned index.