我正在尝试使用 qsort() 对我的数组进行排序,但出现了一个奇怪的错误...
error: passing argument 4 of ‘qsort’ from incompatible pointer type
/usr/include/stdlib.h:761: note: expected ‘__compar_fn_t’ but argument is of
type ‘int (*)(struct Record *, struct Record *)’
这是我的函数调用:
qsort(arr, (sizeof(arr)/sizeof(struct Record)), sizeof(struct Record), compare);
这是我的比较方法:
int compare (struct Record *a, struct Record *b){
return (a->key - b->key);
}
我知道这可能是一个转换问题 - 但我认为我可以直接传递比较函数本身的名称......?
最佳答案
如果你看,错误很明显:__compar_fn_t
的类型是 int(*)(const void*, const void*)
但你的函数是 整数(*)(结构记录*,结构记录*)
。 Quicksort 不知道数组的类型,因此您必须使用 void*
作为比较器参数,然后将它们转换为其中的适当类型:
int compare (const void *a, const void *b){
struct Record const* a_r = (struct Record const*)a,
* b_r = (struct Record const*)b;
return (a_r->key - b_r->key);
}
关于c - 在 C 中使用 qsort/casting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21642320/