C语言Student结构体按姓名升序排序时其余字段错位如何修复?
问题定位
你提供的代码已经足够定位问题,核心错误是排序时仅交换了两个学生结构体的firstName字段,其余所有字段(姓、个人编号、就读类型等)都没有做任何修改,所以才会出现名和其他关联信息不匹配的问题。
修复方案
你需要调整交换逻辑,直接交换整个Student结构体对象而非单个字段,同时补充缺失的排序字段选择逻辑、修正错误的循环跳出逻辑,具体修改如下:
- 把原本用来临时存储名字的字符数组,替换为
struct Student类型的临时变量,用来暂存完整的学生信息 - 交换时直接对整个结构体赋值,不需要逐个字段操作
- 增加对用户输入的
input变量的判断,支持按first name或last name排序 - 去掉不合理的
break逻辑,避免遇到无效学生就直接停止排序
修正后的代码
else if(strcmp(command, "showasc") == 0) { char input[15]; printf("Show in ascendant order by first name or last name?\n "); scanf("%s", input); struct Student copyOfListOfStudents[20]; memcpy(©OfListOfStudents, &listOfStudents, sizeof(listOfStudents)); int i, j; struct Student temp; // 替换原有char s[100],用来暂存完整学生结构体 for(i=0;i<20;i++) { // 跳过无效的i位置学生 if(!copyOfListOfStudents[i].valid) continue; for(j=i+1;j<20;j++) { // 跳过无效的j位置学生 if(!copyOfListOfStudents[j].valid) continue; int cmpRes; // 根据用户选择的排序字段比较 if(strcmp(input, "first") == 0) { cmpRes = strcmp(copyOfListOfStudents[i].firstName, copyOfListOfStudents[j].firstName); } else if(strcmp(input, "last") == 0) { cmpRes = strcmp(copyOfListOfStudents[i].lastName, copyOfListOfStudents[j].lastName); } else { // 输入非法默认按first name排序,可根据需求调整 cmpRes = strcmp(copyOfListOfStudents[i].firstName, copyOfListOfStudents[j].firstName); } if(cmpRes > 0) { // 直接交换整个结构体,所有字段都会同步移动 temp = copyOfListOfStudents[i]; copyOfListOfStudents[i] = copyOfListOfStudents[j]; copyOfListOfStudents[j] = temp; } } } printStudents(copyOfListOfStudents); }
内容的提问来源于stack exchange,提问作者Silverlik
相关产品推荐
相关产品推荐

