qsort and bsearch an array of pointers

∥☆過路亽.° 提交于 2019-12-11 02:54:28

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/6167092/qsort-and-bsearch-an-array-of-pointers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!