结构体存储学生学号、姓名、总分,动态内存分配增加信息,然后排序
1 # include <stdio.h> 2 # include <malloc.h> 3 //# include <windows.h> 4 5 struct stu 6 { 7 char stuno[5]; //学号 8 char sname[10]; //姓名 9 int score; //总分 10 }; 11 12 int main(void) 13 { 14 int n, i, j; 15 struct stu *stuinf, temp; 16 printf("请输入学生个数:"); 17 scanf("%d", &n); 18 printf(" "); 19 stuinf = (struct stu *)malloc(sizeof(struct stu) * n); 20 //输入 21 for (i=0; i<n; i++) 22 { 23 printf("请输入第%d个学生信息: ", i+1); 24 printf("请输入学号:"); 25 scanf("%s", stuinf[i].stuno); 26 printf("请输入姓名:"); 27 scanf("%s", stuinf[i].sname); 28 printf("请输入总分:"); 29 scanf("%d", &stuinf[i].score); 30 printf(" "); 31 } 32 //排序前输出 33 printf("----------排序前:---------- "); 34 for (i=0; i<n; i++) 35 { 36 printf("第%d个学生信息: ", i+1); 37 printf("学号:"); 38 printf("%s ", stuinf[i].stuno); 39 printf("姓名:%s ", stuinf[i].sname); 40 printf("总分:%d ", stuinf[i].score); 41 printf(" "); 42 } 43 //排序 44 for (i=0; i<n-1; i++) 45 { 46 for (j=0; j<n-1-i; j++) 47 { 48 if (stuinf[j].score > stuinf[j+1].score) 49 { 50 temp = stuinf[j]; 51 stuinf[j] = stuinf[j+1]; 52 stuinf[j+1] = temp; 53 } 54 } 55 } 56 57 58 //排序后输出 59 printf("----------排序后:---------- "); 60 for (i=0; i<n; i++) 61 { 62 printf("第%d个学生信息: ", i+1); 63 printf("学号:"); 64 printf("%s ", stuinf[i].stuno); 65 printf("姓名:%s ", stuinf[i].sname); 66 printf("总分:%d ", stuinf[i].score); 67 printf(" "); 68 } 69 //system("pause"); 70 71 return 0; 72 }