gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:11:10 25 4
gpt4 key购买 nike

我写了我的比较函数

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com