Search code examples
clibcqsortbsearch

qsort and bsearch an array of pointers


I need to sort an array of pointers to struc. In fact, I need to do searching among adresses to see if a given pointer to a struct is present in the array. Unfortunately, I don't have nothing "comparable" inside those structures and so I want to sort'em just by address. My code is like that:

item* arr[SIZE];
//something is inserted
qsort(arr, SIZE, sizeof(item*), (void*)compare_funct); 
//CUT
bsearch(curr, arr, SIZE, sizeof(item*), (void*)compare_funct);

I tried creating a compare_funct just casting pointers to int and returning their difference, but it doesn't seem to work. In particular, when I do the bsearch, even if I know that the element is contained inside the array, I always get a NULL as returned value.


Solution

  • int cmp_items(void const *p, void const *q)
    {
        item const *a = *(item const **)p, *b = *(item const **)q;
        return b - a;
    }
    

    (Please don't cast compare_funct to void*. That doesn't do anything except turn off type checking provoke undefined behavior.)

    EDIT: As @R.. points out, the above exhibits undefined behavior unless a and b point into a common array. For full portability (but at the expense of immediate comprehensibility), you should use

    int compare_pointers(void const *p, void const *q)
    {
        return memcmp(p, q, sizeof(item *));
    }