i'm trying sort array of struct records. reason core dump keeps occuring.
when try doing same thing array of ints or structs, works fine. when start using nested structs, begins core dump.
the current output is:
before sorting first last 0 first last 1 first last 2 first last 3 first last 4 first last 5 after sorting segmentation fault (core dumped)
compiler: cygwin
typedef struct { char last[namesize]; /* last name (1 word) */ char first[namesize]; /* first name (1 word) */ } name; typedef struct { name name; int score; /* score (between 0 & 100 inclusive) */ } record; int compare (const void * a, const void * b){ const record *recorda = (record *)a; const record *recordb = (record *)b; printf("%d: %d", recorda->score, recordb->score); return ( recordb->score - recorda->score ); } int main (){ record ** list; int i; list=malloc(6*sizeof(record*)); printf("before sorting\n"); for(i=0; i<6; i++){ list[i]=malloc(sizeof(record)); strcpy(list[i]->name.first,"first"); strcpy(list[i]->name.last,"last"); list[i]->score=i; } (i=0; i<6; i++){ printf ("%s %s %d\n",list[i]->name.first, list[i]- >name.last,list[i]->score); } printf("after sorting\n"); qsort (list, 6, sizeof(record), compare); (i=0; i<6; i++){ printf ("%s %s %d\n",list[i]->name.first, list[i]- >name.last,list[i]->score); } return 0; }
list
array of 6 pointers record
:
list=malloc(6*sizeof(record*));
so need pass same size qsort
.
qsort (list, 6, sizeof(record), compare);
should be
qsort (list, 6, sizeof(record*), compare);
or better yet
qsort (list, 6, sizeof(*list), compare);
Comments
Post a Comment