C 的bsearch
比较函数有两个参数类型转换为void *
。标准是否要求第一个是键,第二个是数据元素?
如果比较函数采用不同类型的键和值,这是相关的。最近看到如下代码:
typedef struct {
unsigned int key;
char *value;
} record;
int cmp_find(const void *val, const void *key) {
return strcmp((char *)val, ((record *)key)->value);
}
以及具有与原始 bsearch
类似签名的自定义搜索功能。如果我使用 bsearch
-compare 函数,这会发生崩溃。
标准甚至允许 bsearch
- 比较具有不同值类型的函数吗?
最佳答案
是的。来自 n1570(C99+修正案/C11):
7.22.5 Searching and sorting utilities
2 The implementation shall ensure that the second argument of the comparison function (when called from
bsearch
), or both arguments (when called fromqsort
), are pointers to elements of the array.302) The first argument when called frombsearch
shall equalkey
.
关于c - 使 C 比较函数对称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27294373/