这是代码,它通过avg运行对板球运动员的数据进行排序.该qsort函数显示错误:
[错误] C:\用户\编码器\文件\ C-免\ TEMP\Untitled3.cpp:29:错误:从无效转变
int (*)(cricketer*, cricketer*)至int (*)(const void*, const void*)[错误] C:\ Users\Encoder\Documents\C-Free\Temp\Untitled3.cpp:29:错误:初始化`void qsort的参数4(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;
}
Run Code Online (Sandbox Code Playgroud)
要传递给它的指针的函数qsort必须是
int sort(const void* va, const void* vb);
Run Code Online (Sandbox Code Playgroud)
因为这是qsort预期的.然后在该功能中你必须在开始时做
const struct cricketer *a = (struct cricketer*) va;
const struct cricketer *b = (struct cricketer*) vb;
Run Code Online (Sandbox Code Playgroud)
或者,如果您更喜欢使用点.而不是箭头访问->
const struct cricketer a = *(struct cricketer*) va;
const struct cricketer b = *(struct cricketer*) vb;
Run Code Online (Sandbox Code Playgroud)
请参阅此参考中的示例
关于错误消息,这int (*)(cricketer*, cricketer*)是一个指向函数的指针,该函数获得2个指针cricketer作为参数.编译器需要这样一个函数指针int (*)(const void, const void*),它告诉你它不能将前者转换为后者.还要注意你需要如何指向const数据,因为sort不应该修改数据.