I have an array of structs and I would like to find a key that is an integer in the array of structs. My structure looks like this:
typedef struct{
int x;
int y;
int area;
int occurence;
}pair;
And I would like to use bsearch()
to find that specific value in the array that is the area. I have an array of pairs sorted by qsort()
in ascending order. My code looks like this:
qsort(pairs, nPairs, sizeof(pair), cmpArea);
int * tmp = NULL, area = someValue;
tmp = (int *)bsearch(&area, pairs, nPairs, sizeof(pair), cmpArea);
if (tmp!=NULL)
//do something
else
//do something
//pairs is the name of the array, nPairs is number of elements
I tried to look at the values using a debugger, and bsearch()
always returns NULL not sure why. I doubt that my compare function is the problem, but it looks like this :
int cmpArea(const void *a, const void *b){
pair * pairA = (pair*)a;
pair * pairB = (pair*)b;
return (pairA->area - pairB->area);
}
I tried different comparing functions, but none works. I´m opened to your ideas. Thank you.
In your code, you are pointing to a key value and not an actual member object.
The call to bsearch
should be more like this:
pair key_obj;
pair *result;
key_obj.area = someValue;
result = bsearch(&key_obj, pairs, nPairs, sizeof(pair), cmpArea);
It was pointed out to me that the first arg could point to an int *
if the comparator was written to handle that. In that case we would have:
int key_obj = someValue;
pair *result;
result = bsearch(&key_obj, pairs, nPairs, sizeof(pair), cmpArea);
int cmpArea(const void *a, const void *b){
int *key = (int *)a;
pair * pairB = (pair*)b;
return (*key - pairB->area);
}