qsort 给出 [错误]:从 `int (*)(cricketer*, cricketer*)' 到 `int (*)(const void*, const void*)' 的无效转换
Posted
技术标签:
【中文标题】qsort 给出 [错误]:从 `int (*)(cricketer*, cricketer*)\' 到 `int (*)(const void*, const void*)\' 的无效转换【英文标题】:qsort gives [Error] : invalid conversion from `int (*)(cricketer*, cricketer*)' to `int (*)(const void*, const void*)'qsort 给出 [错误]:从 `int (*)(cricketer*, cricketer*)' 到 `int (*)(const void*, const void*)' 的无效转换 【发布时间】:2016-02-14 19:53:39 【问题描述】:这是代码,它按平均运行次数对板球运动员的数据进行排序。 qsort
函数显示错误:
[错误] C:\Users\Encoder\Documents\C-Free\Temp\Untitled3.cpp:29: 错误:从
int (*)(cricketer*, cricketer*)
到的无效转换int (*)(const void*, const void*)
[错误] C:\Users\Encoder\Documents\C-Free\Temp\Untitled3.cpp:29: 错误:初始化 `void qsort(void*, size_t, size_t, int ()(const void, const void*))'
包括
#include<stdlib.h>
struct cricketer //structure for details of cricketer
int avg_run;
char name[20];
int age;
int match_no;
c[4];
int sort(struct cricketer *a, struct cricketer *b); //pre-defining sort function
int main() //main function
int i, s;
for (i = 0; i < 3; i++) //enumerating structure records.
printf("enter the name of cricketer ");
fflush(stdin);
gets(c[i].name);
printf("enter his age,his no of matches and total average runs ");
scanf("%d%d%d",&c[i].age, &c[i].match_no, &c[i].avg_run);
printf("records before sorting");
for (i = 0; i < 3; i++)
printf("\n\nname ");
puts(c[i].name);
printf("age %d\nno of matches %d\naverage runs %d\n",c[i].age, c[i].match_no, c[i].avg_run);
qsort(c, 3, sizeof(c[0]), sort); //sorting using qsort
printf("\nrecords after sorting");
for (i = 0; i < 3; i++)
printf("\n\nname ");
puts(c[i].name);
printf("age %d\nno of matches %d\naverage runs %d\n",c[i].age, c[i].match_no, c[i].avg_run);
int sort(struct cricketer *a, struct cricketer *b) //sort function definition
if (a->avg_run == b->avg_run)
return 0;
else
if ( a->avg_run > b->avg_run)
return 1;
else
return -1;
【问题讨论】:
【参考方案1】:你传递给qsort
的函数必须是
int sort(const void* va, const void* vb);
因为这是qsort
所期望的。然后在该功能中,您必须在开始时执行
const struct cricketer *a = (struct cricketer*) va;
const struct cricketer *b = (struct cricketer*) vb;
或者,如果您更喜欢使用点.
而不是箭头->
访问
const struct cricketer a = *(struct cricketer*) va;
const struct cricketer b = *(struct cricketer*) vb;
在reference查看示例
关于错误消息,这个 int (*)(cricketer*, cricketer*)
是一个指向函数的指针,该函数将两个指向 cricketer
的指针作为参数。编译器需要这样一个函数指针int (*)(const void, const void*)
,它告诉您它不能将前者转换为后者。另请注意,您如何需要指向 const 数据的指针,因为 sort 不应该修改数据。
【讨论】:
理想情况下,您希望在这些指针上保留const
限定符。以上是关于qsort 给出 [错误]:从 `int (*)(cricketer*, cricketer*)' 到 `int (*)(const void*, const void*)' 的无效转换的主要内容,如果未能解决你的问题,请参考以下文章