开发者

qsort and bsearch an array of pointers

开发者 https://www.devze.com 2023-03-09 05:26 出处:网络
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 hav

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.


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 *));
}


Look here.

This one describes it pretty well think of it as pointers to struct instead of pointers to char.

Basically the idea is to pass struct** casted to (void*) then you put it back to struct** dereference to get struct* and then just do a compare.

Getting the cast right with qsort can be tricky.

0

精彩评论

暂无评论...
验证码 换一张
取 消