使用qsort对结构体数组按name排序异常及内部元素排序咨询
问题1:结构体数组排序后输出混乱的解决方法
问题原因
你代码里的sum是单独的变长数组,和recipe结构体数组分开存储。当用qsort对recipe排序后,结构体顺序被打乱,但sum数组仍保持原顺序,导致打印时用sum[i]对应排序后的recipe[i],出现索引不匹配问题,甚至越界读取内存产生乱码。
修正方案
把sum字段直接放到node结构体里,让食材数量和对应结构体绑定,排序后数量与结构体的对应关系不会断裂。
修正后的完整代码
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node{ char name[64]; int ingredient_count; // 将sum改为结构体成员,存储当前食谱的食材数量 char ingredient[10][64]; }node; int compare_recipe(const void *a, const void *b){ node *nodeA = (node *)a; node *nodeB = (node *)b; return strcmp(nodeA->name, nodeB->name); } int main(){ int num; scanf("%d", &num); node recipe[num]; // 输入部分 for(int i = 0; i < num; i++){ scanf("%s", recipe[i].name); scanf("%d", &recipe[i].ingredient_count); for(int j = 0; j < recipe[i].ingredient_count; j++){ scanf("%s", recipe[i].ingredient[j]); } } // 排序食谱数组 qsort(recipe, num, sizeof(node), compare_recipe); // 打印输出 printf("\n"); for(int i = 0; i < num; i++){ printf("%s ", recipe[i].name); for(int j = 0; j < recipe[i].ingredient_count; j++){ printf("%s ", recipe[i].ingredient[j]); } printf("\n"); } return 0; }
验证结果
输入测试数据后,输出与预期一致:
bread flour breag breed cake egg flour sugar butter omelet egg bacon ham butter
问题2:给每个结构体的ingredient数组排序的实现方法
实现思路
- 编写字符串比较的回调函数,供
qsort使用; - 遍历每个食谱结构体,对其
ingredient数组调用qsort,注意第二个参数传入当前结构体的ingredient_count(实际食材数量,而非总食谱数num)。
完整实现代码
在问题1的修正代码基础上,添加以下内容:
// 用于比较食材字符串的回调函数 int compare_ingredient(const void *a, const void *b){ return strcmp((const char*)a, (const char*)b); } int main(){ // 保留问题1中的输入、排序食谱数组的代码 // 对每个食谱的食材数组排序 for(int i = 0; i < num; i++){ if(recipe[i].ingredient_count > 0){ // 仅当有食材时排序 qsort(recipe[i].ingredient, recipe[i].ingredient_count, sizeof(recipe[i].ingredient[0]), compare_ingredient); } } // 保留打印输出的代码 }
最终输出结果
运行后得到预期的排序后食材列表:
bread flour breag breed cake butter egg flour sugar omelet bacon butter egg ham
内容的提问来源于stack exchange,提问作者ident
相关产品推荐
相关产品推荐

