c - 在 C 中使用 qsort/casting

标签 c casting qsort

我正在尝试使用 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/

相关文章:

c - PostgreSQL 模块 - 如何将参数数组映射到函数中?

C 宏产生意外行为

Array.SetValue 在运行时的 C# 类型转换

c - 如何在C中对一个非常大的数组进行排序

c - 此值 <stdlib.h> 中的 qsort(浮点二维数组)错误

c - 阻塞套接字

string - 使用 Postgresql 将字符串转换为 Double

java - 隐式类型转换 - Int 到 double

c - 为什么按降序排列的 qsort int 数组不正确?

c - 了解 Linux 中的 RS-485