c语言练习

 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;  
}
  1. 求以下结构体的大小
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,

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值