fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. typedef struct tag_stdata {
  6. int student;
  7. int score;
  8. } stdata;
  9.  
  10. void grow(stdata** pst, int n, int* psz)
  11. {
  12. if (n < *psz) return;
  13. *psz += 10;
  14. if (*pst == NULL) {
  15. *pst = (stdata*)malloc((*psz) * sizeof(stdata));
  16. }
  17. else {
  18. *pst = (stdata*)realloc(*pst, (*psz) * sizeof(stdata));
  19. }
  20. if (*pst == NULL) exit(1);
  21. }
  22.  
  23. int cmp(const void* x, const void* y)
  24. {
  25. return ((stdata*)x)->score - ((stdata*)y)->score;
  26. }
  27.  
  28. int main()
  29. {
  30. char s[80];
  31. stdata* st = NULL;
  32. int stsize, count, i;
  33. stsize = count = 0;
  34. for (;;) {
  35. printf("student[%d]:", count+1);
  36. if (gets(s) == NULL) break;
  37. if (strlen(s) == 0) break;
  38. grow(&st, count, &stsize);
  39. st[count].student = count + 1;
  40. st[count].score = atoi(s);
  41. ++count;
  42. }
  43. qsort((void*)st, count, sizeof(stdata), cmp);
  44. for (i = 0; i < count; i++) {
  45. printf("student[%d]:%d\n", st[i].student, st[i].score);
  46. }
  47. }
  48.  
Success #stdin #stdout 0.01s 2860KB
stdin
10
20
30
15
20
stdout
student[1]:student[2]:student[3]:student[4]:student[5]:student[6]:student[1]:10
student[4]:15
student[2]:20
student[5]:20
student[3]:30