qsort gives [Error] : invalid conversion from `int (*)(cricketer*, cricketer*)' to `int (*)(const void*, const void*)'

后端 未结 1 1904
情话喂你
情话喂你 2021-01-20 16:19

This is the code, it sorts the data of cricketers by avg runs. The qsort function is showing errors:

[Error] C:\\Users\\Encoder\\Document

相关标签:
1条回答
  • 2021-01-20 16:42

    The function whose pointer you pass to qsort must be

    int sort(const void* va, const void* vb);
    

    Because that's what qsort expects. Then within that function you have to do at the beginning

    const struct cricketer *a = (struct cricketer*) va;
    const struct cricketer *b = (struct cricketer*) vb;
    

    Or if you prefer accessing with dots . instead of arrows ->

    const struct cricketer a = *(struct cricketer*) va;
    const struct cricketer b = *(struct cricketer*) vb;
    

    See an example at this reference

    Regarding the error message, this int (*)(cricketer*, cricketer*) is a pointer to a function that gets 2 pointers to cricketer as arguments. The compiler expects such a function pointer int (*)(const void, const void*) and it's telling you it cannot convert the former to the latter. Also note how you need pointer to const data as sort is not supposed to modify the data.

    0 讨论(0)
提交回复
热议问题