qsort给出[错误]:来自`int(*)(cricketer *,cricketer *)'的无效转换到`int(*)(const void *,const void *)'

时间:2015-11-13 09:13:28

标签: c qsort

这是代码,它通过avg运行对板球运动员的数据进行排序。 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的参数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;
}

1 个答案:

答案 0 :(得分:6)

您传递给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*)是一个指向函数的指针,该函数获得2个指向cricketer的指针作为参数。编译器期望这样的函数指针int (*)(const void, const void*),它告诉你它不能将前者转换为后者。还要注意你需要如何指向const数据,因为sort不应该修改数据。