passing argument 4 of 'qsort' from incompatible pointer type

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

I'm having some trouble with a function we are supposed to be writing. Supposedly, this is how it should work, but it's giving me the incompatible pointer type error and I'm not sure how to fix it.

The issue is in the qsort referencing the compare_last function.

#include <stdio.h> #include <string.h> #include <stdlib.h>  #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, "<html>\n<body>\n<title>LAB14</title>\n");      for(j = 0; j < i; j++)     {         fprintf(fptrout, "%s %s %i <br>", musicians[j].last, musicians[j].first, musicians[j].year);     }      fprintf(fptrout, "</body>\n</html>\n");     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);  } 

回答1:

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

should be

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

Then you need to cast within compare_last



回答2:

The prototype for qsort() is:

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

Thus, your sorting function needs to either match int(*compar)(const void *, const void *), or you need to cast when calling qsort().

If you want to sort Person*, the easiest way is to declare your sorting function as required, then cast inside the function:

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

there's no need at all to cast then, since const void * converts just fine to const Person *.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!