Sorting a list of students by name and grade using struct in C -
i'm writing program sorts list of students name , grade. i'm receiving following errors when attempt compile:
ex11.c: in function 'comparebygrade': ex11.c:46: error: request member 'grade' in not structure or union ex11.c:47: error: request member 'grade' in not structure or union ex11.c: in function 'comparebyname': ex11.c:56: error: request member 'name' in not structure or union ex11.c:57: error: request member 'name' in not structure or union
this header file:
#define class_size 10 struct student { char *name; int idnumber; char grade; };
this main file:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "ex11.h" int main(void) { int c, i; file *data; struct student tmp, class[class_size]; void *namearray[class_size], *gradearray[class_size]; static int comparebygrade(const void *first, const void *second); static int comparebyname(const void *first, const void *second); data = fopen("data", "r"); /* open data file */ /* move data struct */ (i = 0; < class_size; ++i) { fscanf(data, "%s%d%c", tmp.name, tmp.idnumber, tmp.grade); class[i].name = tmp.name; class[i].idnumber = tmp.idnumber; class[i].grade = tmp.grade; } fclose(data); /* close data file */ qsort(namearray, class_size, sizeof(*namearray), &comparebyname); qsort(gradearray, class_size, sizeof(*gradearray), &comparebygrade); } /* function sorty grade */ static int comparebygrade(const void *first, const void *second) { const char *firstgrade = (*(const char **) first) -> grade; /* line 46 */ const char *secondgrade = (*(const char **) second) -> grade; /* line 47 */ return strcmp(firstgrade, secondgrade); } /* function sort name */ static int comparebyname(const void *first, const void *second) { const char *firstname = (*(const char **) first) -> name; /* line 56 */ const char *secondname = (*(const char **) second) -> name; /* line 57 */ return strcmp(firstname, secondname); }
what doing wrong?
agreed xaxxon. program processes struct student class, namearray , gradearray never initialized.
btw,i suppose not use struct named class, it's confused c++'s keyword.
grade char, strcmp() need string compare.
suggestion: in main(),
qsort(class, class_size, sizeof(struct student*), &comparebyname); qsort(class, class_size, sizeof(struct student*), &comparebygrade);
and outside,
int comparebygrade(const void *first, const void *second) { const char firstgrade = ((struct student *)first) -> grade; const char secondgrade = ((struct student *)second) -> grade; return firstgrade<secondgrade?-1:(firstgrade==secondgrade?0:1); } /* function sort name */ int comparebyname(const void *first, const void *second) { const char *firstname = ((struct student *)first) -> name; const char *secondname = ((struct student *)second) -> name; return strcmp(firstname, secondname); }
the expression of return value of comparebygrade() act in same way of comparebyname()
Comments
Post a Comment