1.从堆区申请能存5个结构体变量的数组的空间,完成数组中成员的输入,根据学生成绩,用选择排序的方式,对学生排序并输出。
#include <stdio.h>
// 定义学生结构体
typedef struct {
int id;
char name[50];
int score;
} Student;
// 交换两个学生的成绩
void swapScores(Student students[], int i, int j) {
int temp = students[i].score;
students[i].score = students[j].score;
students[j].score = temp;
}
// 选择排序函数
void selectionSort(Student students[], int n) {
int i, j, minIndex;
for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++) {
if (students[j].score > students[minIndex].score) { // 假设按成绩降序排序
minIndex = j;
}
}
if (minIndex != i) {
swapScores(students, i, minIndex);
}
}
}
int main() {
int i;
Student students[5];
// 输入学生信息
for (i = 0; i < 5; ++i) {
printf("请输入名字和分数 %d:\n", i + 1);
scanf("%s %d", students[i].name, &students[i].score);
}
// 选择排序
selectionSort(students, 5);
// 输出排序后的学生信息
printf("\nSorted students:\n");
for (i = 0; i < 5; ++i) {
printf("Name: %s, ID: %d, Score: %d\n", students[i].name, students[i].score);
}
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;
typedef struct {
int id; // 通常int是4字节(32位系统)或8字节(64位系统)
char name[50]; // 50字节的字符数组
char grade[3]; // 3字节的字符数组
} Student;
typedef struct {
int id; // 4字节
char name[50]; // 50字节
Student student; // 60
}Teacher //114
typedef struct {
int id; // 4字节
char name[50]; // 50字节
Teacher teacher; // 114
} Course; 168
Student
结构体的大小至少会是4 + 50 + 3 = 57-->对齐到60字节
Teacher
结构体包含一个int
、一个50字节的字符数组,以及一个Student
类型的成员。Teacher
的大小至少是4 + 50 + 60=114,
Course
结构体包含一个int
、一个50字节的字符数组,以及一个Teacher
类型的成员。Course
的大小至少是4 + 50 + 114
字节=168,