c - 在 C 中使用 qsort 时的警告

标签 c qsort

我写了我的比较函数

int cmp(const int * a,const int * b)
 {
   if (*a==*b)
   return 0;
else
  if (*a < *b)
    return -1;
else
    return 1;
}

我有我的声明

int cmp (const int * value1,const int * value2);

我在我的程序中这样调用 qsort

qsort(currentCases,round,sizeof(int),cmp);

当我编译它时,我收到以下警告

warning: passing argument 4 of ‘qsort’ from incompatible pointer type
/usr/include/stdlib.h:710: note: expected ‘__compar_fn_t’ but argument is of type ‘int
(*)(const int *, const int *)’

该程序运行良好,所以我唯一担心的是为什么它不喜欢我使用它的方式?

最佳答案

cmp 函数的原型(prototype)必须是

int cmp(const void* a, const void* b);

您可以在调用 qsort 时强制转换它(不推荐):

qsort(currentCases, round, sizeof(int), (int(*)(const void*,const void*))cmp);

或者在 cmp 中将 void 指针转换为 int 指针(标准方法):

int cmp(const void* pa, const void* pb) {
   int a = *(const int*)pa;
   int b = *(const int*)pb;
   ...

关于c - 在 C 中使用 qsort 时的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2561697/

相关文章:

c - 内存访问冲突不会在 c 中给出任何错误

c - C 中的双重自由或腐败 3d 数组

C - 大约 30 次读取后无法读取套接字

c - fatal error : stdio. h:没有那个文件或目录

c - 一个数组相对于另一个数组的 qsort()

C - 按计数然后按字母顺序 Qsort

将一个图像文件复制到另一个图像文件

c++ - qsort线程安全吗?

字符串指针数组中的 C char qsort

c - 对除第一个元素之外的所有内容进行排序,qsort C