从堆区申请能存5个结构体变量的数组的空间,完成数组中成员的输入,根据学生成绩,用选择排序的方式,对学生排序并输出
#include <stdlib.h>
typedef struct { // 先定义学生的结构体
int id;/ID
char name[50]; //姓名
float score; //成绩
} Student;
int compare(const void *a,const void *b) { //比较函数,用来选择排序
Student *studentA=(Student *)a;
Student *studentB=(Student *)b;
return studentA->score - studentB ->score;
}
int main(){
Student *students =(Student *)malloc(5 * sizeof(Student));//从堆区申请5个结构体变量的数组的空间
if(students == NULL){
printf(“内存分配失败”);
return EXIT_FAILURE;
}
for(int i=0;i<5;i++){ //输入组中成员信息
printf("输入学生信息 %d:\n",i+1);
printf("ID:");
scanf("%d",&students[i].id);
printf("Name:");
scanf("%s",students[i].name);
printf("Score:");
scanf("%f",&students[i].score);
}
qsort(students,5,sizeof(Student),compare);//使用选择排序对学生按成绩排序
printf(“按分数排序的学生\n:");
for(int i=0;i<5;i++){
printf("ID:%d Name:%s Score:%.2f\n",students[i].id,students[i].name,students[i].score);
}
free(students);
return 0;
}
求以下结构体的大小
typedef struct {
int id;
char name[50];
char grade[3];
} student;
typedef struct {
int id;
char name[50];
student student;
} Teacher;
typedef struct {
int id;
char name[50];
Teacher teacher;
} Course;
先计算student的结构体
int id;id成员占用4个字节,
char name;name成员是一个一维字符数组,占用了50个字节,
char grade;grade成员是一个一维字符数组,占用了3个字节
正常计算是 4+50+3=57个字节,但是由于结构体大小会满足字节对齐的原则,正常按照4的倍数进行对齐 也就是60字节 正好是4的倍数
接下来计算Teacher的结构体
int id;id成员占用4个字节,
char name;name成员是一个一维字符数组,占用了50个字节,
student student;student成员是前面计算的 student结构体的大小,按60字节来计算
也就是4+50+60=114字节 ,如果对齐的话 是116字节
最后计算Course的结构体
int id;id成员占用4个字节,
char name;name成员是一个一维字符数组,占用了50个字节,
Teacher teacher;teacher成员是前面计算的 teacher的结构体大小 按116字节来算
就是 4+50+116=170个字节大小 ,如果对其的话 是172个字节 正好是4的倍数,
具体情况需要具体看操作系统的对齐量,32位操作系统默认4字节对齐,64位操作系统默认8字节对齐。