qsort和bsearch指针数组 [英] qsort and bsearch an array of pointers

查看:109
本文介绍了qsort和bsearch指针数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对指向struc的指针进行排序.实际上,我需要在地址之间进行搜索,以查看数组中是否存在指向结构的给定指针.不幸的是,我在这些结构中没有什么可比的,因此我只想按地址对它们进行排序. 我的代码是这样的:

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

我尝试创建一个compare_funct,只是将指针转换为int并返回它们的差值,但这似乎不起作用.特别是,当我执行bsearch时,即使我知道该元素包含在数组中,我也总是得到NULL作为返回值.

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

(请不要将compare_funct强制转换为void*.除了关闭类型检查会引发未定义的行为之外,这不会做任何事情.)

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

编辑:正如@R ..指出的那样,除非ab指向一个公共数组,否则上面的内容将显示未定义的行为.为了获得完全的可移植性(但要以立即理解为代价),您应该使用

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

这篇关于qsort和bsearch指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆