void sort() { if (count == 0) { printf("通讯录为空,无法统计排序!\n"); return; } char hometown[20]; printf("请输入要统计排序的籍贯:"); scanf("%s", hometown); int i, j; int num = 0; for (i = 0; i < count; i++) { if (strcmp(book[i].hometown, hometown) == 0) { num++; } } if (num == 0) { printf("未找到该籍贯的学生!\n"); return; } Student *students = (Student *)malloc(num * sizeof(Student)); if (students == NULL) { printf("内存分配失败!\n"); return; } int k = 0; for (i = 0; i < count; i++) { if (strcmp(book[i].hometown, hometown) == 0) { students[k++] = book[i]; } } // 冒泡排序 for (i = 0; i < num - 1; i++) { for (j = 0; j < num - 1 - i; j++) { if (strcmp(students[j].name, students[j + 1].name) > 0) { Student temp = students[j]; students[j] = students[j + 1]; students[j + 1] = temp; } } } printf("姓名\t性别\t籍贯\t电话\n"); for (i = 0; i < num; i++) { printf("%s\t%s\t%s\t%s\n", students[i].name, students[i].sex, students[i].hometown, students[i].phone); } free(students); }请为这段代码添加注释
时间: 2024-02-14 08:09:54 浏览: 26
下面是注释后的代码:
void sort() {
// 判断通讯录是否为空
if (count == 0) {
printf("通讯录为空,无法统计排序!\n");
return;
}
// 读取用户输入的籍贯
char hometown[20];
printf("请输入要统计排序的籍贯:");
scanf("%s", hometown);
int i, j;
int num = 0;
// 统计籍贯匹配的记录数量
for (i = 0; i < count; i++) {
if (strcmp(book[i].hometown, hometown) == 0) {
num++;
}
}
// 如果未找到匹配的记录,则输出提示信息并返回
if (num == 0) {
printf("未找到该籍贯的学生!\n");
return;
}
// 动态分配内存存储符合要求的记录
Student *students = (Student *)malloc(num * sizeof(Student));
if (students == NULL) {
printf("内存分配失败!\n");
return;
}
// 将符合要求的记录存储到动态分配的内存中
int k = 0;
for (i = 0; i < count; i++) {
if (strcmp(book[i].hometown, hometown) == 0) {
students[k++] = book[i];
}
}
// 对记录按姓名进行冒泡排序
for (i = 0; i < num - 1; i++) {
for (j = 0; j < num - 1 - i; j++) {
if (strcmp(students[j].name, students[j + 1].name) > 0) {
Student temp = students[j];
students[j] = students[j + 1];
students[j + 1] = temp;
}
}
}
// 输出排序后的记录
printf("姓名\t性别\t籍贯\t电话\n");
for (i = 0; i < num; i++) {
printf("%s\t%s\t%s\t%s\n", students[i].name, students[i].sex, students[i].hometown, students[i].phone);
}
// 释放动态分配的内存
free(students);
}
该函数主要实现以下功能:
1. 判断通讯录是否为空,若为空则无法统计排序,输出提示信息并返回。
2. 读取用户输入的籍贯。
3. 统计籍贯匹配的记录数量,如果未找到匹配的记录,则输出提示信息并返回。
4. 动态分配内存存储符合要求的记录。
5. 将符合要求的记录存储到动态分配的内存中。
6. 对记录按姓名进行冒泡排序。
7. 输出排序后的记录。
8. 释放动态分配的内存。
需要注意的是,该函数的动态内存分配部分需要慎重考虑,在实际应用中需要注意内存泄漏和内存安全等问题。