C: 实战:自定义类型综合
学了这么多,该动手造东西了。就像学做菜,光看食谱不够,得上灶台——把结构体、动态内存、文件操作串起来,做出能用的程序。
1. 项目一:学生成绩管理系统
(1) 需求分析
- 添加学生(姓名、学号、三门成绩)
- 显示所有学生信息
- 按学号查找
- 计算每人的总分和平均分
- 按总分排序
- 保存到文件 / 从文件加载
- 动态内存管理,学生数量不固定
(2) 数据结构设计
C
// 类型定义
typedef struct {
char name[32];
char id[16];
// 变量声明
int chinese;
// 变量声明
int math;
// 变量声明
int english;
} Student;
// 类型定义
typedef struct {
Student *data;
// 变量声明
int count;
// 变量声明
int capacity;
} StudentList;
StudentList 用动态数组管理学生,初始容量 4,不够时扩容。
(3) 核心实现
C
// 预处理指令
#include <stdio.h>
// 预处理指令
#include <stdlib.h>
// 预处理指令
#include <string.h>
// 类型定义
typedef struct {
char name[32];
char id[16];
// 变量声明
int chinese;
// 变量声明
int math;
// 变量声明
int english;
} Student;
// 类型定义
typedef struct {
Student *data;
// 变量声明
int count;
// 变量声明
int capacity;
} StudentList;
// 函数定义
void list_init(StudentList *list) {
list->capacity = 4;
list->count = 0;
list->data = (Student *)malloc(sizeof(Student) * list->capacity);
}
// 函数定义
void list_free(StudentList *list) {
// 动态内存操作
free(list->data);
list->data = NULL;
list->count = 0;
list->capacity = 0;
}
// 函数定义
void list_expand(StudentList *list) {
// 条件判断
if (list->count < list->capacity) return;
list->capacity *= 2;
Student *tmp = (Student *)realloc(list->data, sizeof(Student) * list->capacity);
// 条件判断
if (tmp) list->data = tmp;
}
// 函数定义
void list_add(StudentList *list, const Student *s) {
list_expand(list);
list->data[list->count++] = *s;
}
// 函数定义
int total_score(const Student *s) {
// 返回结果
return s->chinese + s->math + s->english;
}
// 函数定义
double avg_score(const Student *s) {
// 返回结果
return total_score(s) / 3.0;
}
Student *find_by_id(StudentList *list, const char *id) {
// for 循环
for (int i = 0; i < list->count; i++) {
// 条件判断
if (strcmp(list->data[i].id, id) == 0) {
// 返回结果
return &list->data[i];
}
}
// 返回结果
return NULL;
}
// 函数定义
int cmp_by_total(const void *a, const void *b) {
// 变量声明
int ta = total_score((const Student *)a);
// 变量声明
int tb = total_score((const Student *)b);
// 返回结果
return tb - ta;
}
// 函数定义
void sort_by_total(StudentList *list) {
qsort(list->data, list->count, sizeof(Student), cmp_by_total);
}
// 函数定义
void print_student(const Student *s) {
// 输入输出操作
printf("%-6s %-10s 语文:%-3d 数学:%-3d 英语:%-3d 总分:%-4d 均分:%.1f\n",
s->id, s->name, s->chinese, s->math, s->english,
total_score(s), avg_score(s));
}
// 函数定义
void print_all(const StudentList *list) {
// 输入输出操作
printf("学号 姓名 语文 数学 英语 总分 均分\n");
// 输入输出操作
printf("----------------------------------------------------------\n");
// for 循环
for (int i = 0; i < list->count; i++) {
print_student(&list->data[i]);
}
}
// 函数定义
int save_to_file(const StudentList *list, const char *filename) {
FILE *fp = fopen(filename, "w");
// 条件判断
if (!fp) return -1;
fprintf(fp, "%d\n", list->count);
// for 循环
for (int i = 0; i < list->count; i++) {
Student *s = &list->data[i];
fprintf(fp, "%s %s %d %d %d\n", s->id, s->name,
s->chinese, s->math, s->english);
}
// 输入输出操作
fclose(fp);
// 返回结果
return 0;
}
// 函数定义
int load_from_file(StudentList *list, const char *filename) {
FILE *fp = fopen(filename, "r");
// 条件判断
if (!fp) return -1;
// 变量声明
int n;
fscanf(fp, "%d", &n);
// for 循环
for (int i = 0; i < n; i++) {
Student s;
fscanf(fp, "%s %s %d %d %d", s.id, s.name,
&s.chinese, &s.math, &s.english);
list_add(list, &s);
}
// 输入输出操作
fclose(fp);
// 返回结果
return 0;
}
▶ 示例
▶ 试一试
TEXT
--- 所有学生 ---
学号 姓名 语文 数学 英语 总分 均分
----------------------------------------------------------
001 Alice 语文:85 数学:92 英语:78 总分:255 均分:85.0
002 Bob 语文:90 数学:88 英语:95 总分:273 均分:91.0
003 Carol 语文:72 数学:65 英语:80 总分:217 均分:72.3
--- 按总分排序 ---
学号 姓名 语文 数学 英语 总分 均分
----------------------------------------------------------
002 Bob 语文:90 数学:88 英语:95 总分:273 均分:91.0
001 Alice 语文:85 数学:92 英语:78 总分:255 均分:85.0
003 Carol 语文:72 数学:65 英语:80 总分:217 均分:72.3
查找001: Alice 总分=255
已保存到 students.dat
2. 项目二:通讯录管理
(1) 需求分析
- 添加联系人(姓名、电话、邮箱、分组)
- 按姓名查找
- 按分组筛选
- 删除联系人
- 修改联系人信息
- 保存到文件 / 从文件加载
(2) 数据结构设计
C
// 类型定义
typedef struct {
char name[32];
char phone[16];
char email[40];
char group[16];
} Contact;
// 类型定义
typedef struct {
Contact *data;
// 变量声明
int count;
// 变量声明
int capacity;
} ContactList;
(3) 核心实现
C
// 预处理指令
#include <stdio.h>
// 预处理指令
#include <stdlib.h>
// 预处理指令
#include <string.h>
// 类型定义
typedef struct {
char name[32];
char phone[16];
char email[40];
char group[16];
} Contact;
// 类型定义
typedef struct {
Contact *data;
// 变量声明
int count;
// 变量声明
int capacity;
} ContactList;
// 函数定义
void clist_init(ContactList *list) {
list->capacity = 4;
list->count = 0;
list->data = (Contact *)malloc(sizeof(Contact) * list->capacity);
}
// 函数定义
void clist_free(ContactList *list) {
// 动态内存操作
free(list->data);
list->data = NULL;
list->count = 0;
list->capacity = 0;
}
// 函数定义
void clist_expand(ContactList *list) {
// 条件判断
if (list->count < list->capacity) return;
list->capacity *= 2;
Contact *tmp = (Contact *)realloc(list->data, sizeof(Contact) * list->capacity);
// 条件判断
if (tmp) list->data = tmp;
}
// 函数定义
void clist_add(ContactList *list, const Contact *c) {
clist_expand(list);
list->data[list->count++] = *c;
}
// 函数定义
int clist_remove(ContactList *list, const char *name) {
// for 循环
for (int i = 0; i < list->count; i++) {
// 条件判断
if (strcmp(list->data[i].name, name) == 0) {
list->data[i] = list->data[list->count - 1];
list->count--;
// 返回结果
return 0;
}
}
// 返回结果
return -1;
}
Contact *clist_find(ContactList *list, const char *name) {
// for 循环
for (int i = 0; i < list->count; i++) {
// 条件判断
if (strcmp(list->data[i].name, name) == 0) {
// 返回结果
return &list->data[i];
}
}
// 返回结果
return NULL;
}
// 函数定义
void clist_filter_by_group(const ContactList *list, const char *group) {
// 输入输出操作
printf("--- 分组: %s ---\n", group);
// for 循环
for (int i = 0; i < list->count; i++) {
// 条件判断
if (strcmp(list->data[i].group, group) == 0) {
// 输入输出操作
printf("%s %s %s\n", list->data[i].name,
list->data[i].phone, list->data[i].email);
}
}
}
// 函数定义
void print_contact(const Contact *c) {
// 输入输出操作
printf("%-8s %-14s %-24s %s\n", c->name, c->phone, c->email, c->group);
}
// 函数定义
void print_all_contacts(const ContactList *list) {
// 输入输出操作
printf("%-8s %-14s %-24s %s\n", "姓名", "电话", "邮箱", "分组");
// 输入输出操作
printf("---------------------------------------------------------\n");
// for 循环
for (int i = 0; i < list->count; i++) {
print_contact(&list->data[i]);
}
}
// 函数定义
int save_contacts(const ContactList *list, const char *filename) {
FILE *fp = fopen(filename, "w");
// 条件判断
if (!fp) return -1;
fprintf(fp, "%d\n", list->count);
// for 循环
for (int i = 0; i < list->count; i++) {
Contact *c = &list->data[i];
fprintf(fp, "%s %s %s %s\n", c->name, c->phone, c->email, c->group);
}
// 输入输出操作
fclose(fp);
// 返回结果
return 0;
}
// 函数定义
int load_contacts(ContactList *list, const char *filename) {
FILE *fp = fopen(filename, "r");
// 条件判断
if (!fp) return -1;
// 变量声明
int n;
fscanf(fp, "%d", &n);
// for 循环
for (int i = 0; i < n; i++) {
Contact c;
fscanf(fp, "%s %s %s %s", c.name, c.phone, c.email, c.group);
clist_add(list, &c);
}
// 输入输出操作
fclose(fp);
// 返回结果
return 0;
}
▶ 示例
▶ 试一试
TEXT
--- 全部联系人 ---
姓名 电话 邮箱 分组
---------------------------------------------------------
Alice 13800001111 alice@mail.com 同事
Bob 13900002222 bob@mail.com 朋友
Carol 15000003333 carol@mail.com 同事
赵六 18600004444 zhaoliu@mail.com 家人
--- 分组: 同事 ---
Alice 13800001111 alice@mail.com
Carol 15000003333 carol@mail.com
查找Bob: 13900002222 bob@mail.com
--- 删除Carol后 ---
姓名 电话 邮箱 分组
---------------------------------------------------------
Alice 13800001111 alice@mail.com 同事
Bob 13900002222 bob@mail.com 朋友
赵六 18600004444 zhaoliu@mail.com 家人
已保存到 contacts.dat
3. 综合要点回顾
(1) 动态数组的模式
两个项目都用了相同的动态数组模式:
这是 C 语言中最常用的动态集合实现方式,掌握后可以复用到各种场景。
(2) 文件读写的模式
C
fprintf(fp, "%d\n", count);
// for 循环
for (int i = 0; i < count; i++) {
fprintf(fp, "字段1 字段2 ...\n", ...);
}
读取时先读个数,再循环读取每条记录。注意用 %s 读字符串时字段间不能有空格,或者用 fscanf 配合固定格式。
(3) 删除的技巧
删除数组中间元素时,用最后一个元素覆盖被删元素,然后 count--。这不需要移动大量元素,但不保持原顺序。如需保持顺序,用 memmove 移动后续元素。
▶ 示例
前面两个项目都依赖「数据结构 + 动态数组」,这里把它们抽成最小可运行版本:容量不够自动翻倍、删除时用末尾元素覆盖,一次看清扩容时机和删除代价。
▶ 展开运行示例(62 行)
TEXT
扩容: capacity = 2
扩容: capacity = 4
人数: 3, 平均分: 85.67, 容量: 4
删除后: Carol Bob
前两次 add 触发扩容,第三次刚好落在容量 4 里;删除用末尾覆盖,所以顺序被打乱但不需要搬移元素。
❓ 常见问题
Q C语言学生成绩管理系统怎么设计?
A 先定三件事:数据结构(
struct Student 存学号、姓名、成绩)、容器(data + count + capacity 的动态数组)、操作(增删改查 + 存盘)。 再按菜单把每个功能拆成一个函数,主函数只负责循环读选项并分发。这样结构清晰,也方便把同一套骨架套到通讯录上。Q 学生信息用什么结构存,结构体数组怎么初始化?
A 固定人数用结构体数组,人数不定就用动态数组。 固定写法
struct Student a[3] = {{1, "Alice", 88.5}, {2, "Bob", 92.0}};;想先清零就写 struct Student a[3] = {0};,后续再逐条赋值。数组长度用 sizeof a / sizeof a[0] 计算,但只能在数组还没退化成指针的作用域里算。Q 学生人数不确定时,怎么用 malloc 做动态数组?
A 先申请一个小容量,装满后
realloc 翻倍。 典型结构是 Student *data; int count; int capacity;:data = malloc(cap * sizeof *data),每次追加前判断 count == capacity,满了把容量乘 2 再 realloc。realloc 可能搬移地址,必须用临时指针接住返回值再赋回,最后记得 free。Q 怎么按成绩给学生排序?
A 用
qsort 加自定义比较函数最省事,字段少时冒泡也行。 调用写 qsort(list.data, list.count, sizeof(Student), cmp_score),比较函数内部把两个 void * 转回 Student * 再比较 score。降序写成 return (sb->score > sa->score) - (sb->score < sa->score);,不要直接返回浮点相减的结果。Q 学生信息怎么保存到文件?
A 先写记录条数,再逐条写字段,读取时就知道要读几条。 文本格式用
fprintf(fp, "%d %s %lf\n", s.id, s.name, s.score),二进制格式用 fwrite(&s, sizeof s, 1, fp)。文本可读可手改,二进制紧凑但跨平台要小心对齐和字节序。写完必须 fclose,否则缓冲区里的数据可能没落盘。Q 程序重启后怎么把数据读回来?
Q 删除一个学生记录怎么写?
A 找到下标后,用最后一个元素覆盖它再
count--;要保序就用 memmove 前移。 覆盖法只需一次赋值,适合不关心顺序的场景;保序写法是 memmove(&data[i], &data[i + 1], (count - i - 1) * sizeof *data)。删除时不要 free 单条记录(它不是独立分配的),只有整个容器销毁时才 free(data)。Q 通讯录管理系统和成绩管理系统有什么不同?
A 结构不同、套路相同。 通讯录记录姓名、电话、邮箱、分组,成绩管理记录学号、姓名、分数,两者都要增删改查和存盘。差别主要在查找条件(按姓名模糊查、按分组筛选)和显示格式(表格对齐)。把动态数组和文件读写抽成公共函数,两个项目可以共用同一套底层代码。
📖 小节
- 动态数组用
指针+count+capacity结构管理,扩容用 2 倍策略 - 增删查改是数据管理的核心操作,每个项目都围绕这四项展开
- 文件保存先写记录数再逐条写,读取时先读数再逐条读
- 删除中间元素可用末尾覆盖法(快但无序)或移位法(保序)
- 结构体、动态内存、文件操作三者结合是 C 语言项目的基本模式
📝 作业
- 为学生成绩管理系统添加"修改成绩"功能:输入学号和新成绩,更新对应学生记录
- 为通讯录添加"按电话号码查找"功能,并将通讯录改为按姓名排序存储(插入时保持有序)
- 将两个项目拆分成多文件结构:每个项目至少有
.h声明文件和.c实现文件,编写对应的 Makefile