c/c++语言开发共享从不兼容的指针类型传递’qsort’的参数4

我在编写一个我们应该写的函数时遇到了一些麻烦。 据说,这是它应该如何工作,但它给了我不兼容的指针类型错误,我不知道如何解决它。

问题出在引用compare_last函数的qsort中。

#include  #include  #include  #define MAX_PERSONS 100 //person structure definition goes here typedef struct{ char last[32]; char first[32]; int year; }Person; //function declarations go here int compare_last(Person * ptr1, Person * ptr2); void main(void){//main function goes here char *infilename[20]; char *outfilename[20]; FILE * fptrin; FILE * fptrout; int i, j; Person musicians[MAX_PERSONS]; printf("Enter input file name: "); scanf("%s", infilename); printf("Enter output file name: "); scanf("%s", outfilename); strcat(*outfilename, ".htm"); fptrin = fopen(*infilename, "r"); fptrout = fopen(*outfilename, "w"); for(i = 0; i < MAX_PERSONS; i++) { fscanf(fptrin, "%s %s %i", musicians[i].last, musicians[i].first, &musicians[i].year); } qsort(musicians, i, sizeof(musicians[0]), compare_last); fprintf(fptrout, "nnLAB14n"); for(j = 0; j < i; j++) { fprintf(fptrout, "%s %s %i 
", musicians[j].last, musicians[j].first, musicians[j].year); } fprintf(fptrout, "nn"); fclose(fptrin); fclose(fptrout); }//end main //function definitions go here int compare_last(Person * ptr1, Person * ptr2) { int result = strcmp(ptr1 -> last, ptr2 -> last); if(result != 0) return result; else return strcmp(ptr1 -> first, ptr2 -> first); }

     int compare_last(Person * ptr1, Person * ptr2); 

    应该

     int compare_last(void * ptr1, void * ptr2); 

    然后你需要在compare_last

    qsort()的原型是:

     void qsort(void *base, size_t nmemb, size_t size, int(*compar)(const void *, const void *)); 

    因此,您的排序函数需要匹配int(*compar)(const void *, const void *) ,或者在调用qsort()时需要强制转换。

    如果要对Person*进行排序,最简单的方法是根据需要声明排序函数,然后在函数内部进行转换:

     static int compare_last(const void *ptr1, const void *ptr2) { const Person *p1 = ptr1, *p2 = ptr2; int result = strcmp(p1 -> last, p2 -> last); ... } 

    因为const void *转换为const Person * ,所以根本不需要const void *转换。

      以上就是c/c++开发分享从不兼容的指针类型传递’qsort’的参数4相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/550132.html

      (0)
      上一篇 2021年1月14日
      下一篇 2021年1月14日

      精彩推荐