You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何基于int字段对结构体数组排序并按序展示

解决方案:使用标准库qsort对结构体数组按nummer字段排序

首先,C标准库提供的qsort函数是处理这类排序需求的最优选择——它实现了高效的快速排序算法,无需手动编写排序逻辑,既可靠又节省时间。

步骤1:编写比较函数

qsort需要一个自定义的比较函数,用来告诉它如何比较两个结构体元素。对于你的vara结构体,我们需要按nummer(整数类型)升序排序,比较函数可以这么写:

// 比较两个vara结构体的nummer字段
int compareVara(const void *a, const void *b) {
    const struct vara *varaA = (const struct vara *)a;
    const struct vara *varaB = (const struct vara *)b;
    // 升序排序:如果a的nummer小于b,返回负数;相等返回0;大于返回正数
    return varaA->nummer - varaB->nummer;
    // 如果要降序排序,反过来写:return varaB->nummer - varaA->nummer;
}

解释:

  • 函数参数是const void*类型,这是qsort要求的通用指针类型,我们需要把它们转换成const struct vara*来访问结构体字段。
  • 返回值规则:qsort根据返回值的正负/零来判断两个元素的相对顺序,完全符合整数比较的逻辑。

步骤2:在读取完CSV数据后调用qsort

在你的代码中,读取CSV的循环结束后,i变量的值就是实际读取到的结构体元素数量(注意不是固定的100),这时候调用qsort即可:

// 对items数组按nummer字段排序
qsort(items, i, sizeof(struct vara), compareVara);

参数说明:

  • items:要排序的数组首地址
  • i:数组中实际的元素个数
  • sizeof(struct vara):每个数组元素的字节大小
  • compareVara:我们刚才定义的比较函数

步骤3:排序后输出验证

排序完成后,你可以再循环遍历数组,输出每个元素的nummer和其他字段,就能看到按顺序排列的结果了:

// 排序后输出所有条目
printf("=== 按nummer升序排序后的结果 ===\n");
for (int j = 0; j < i; j++) {
    printf("nummer: %d\nnamn: %s\npris: %f\nvolym: %f\ntyp: %s\nstil: %s\nforpackning: %s\nland: %s\nproducent: %s\nalkoholhalt: %f\n\n",
           items[j].nummer, items[j].namn, items[j].pris, items[j].volym,
           items[j].typ, items[j].stil, items[j].forpackning, items[j].land,
           items[j].producent, items[j].alkoholhalt);
}

额外的小提示:修复strncpy的潜在越界问题

看你代码里的strncpy调用,比如这一行:

strncpy(items[i].namn, tok, (max(strlen(tok), sizeof(items[0].namn))));

这里应该用min而不是max!因为strncpy的第三个参数是最大复制长度,如果用max,当tok的长度超过namn数组的大小(100)时,会复制超过数组容量的内容,导致缓冲区溢出,这是非常危险的。正确的写法应该是:

strncpy(items[i].namn, tok, sizeof(items[0].namn) - 1); // 留一个字节给终止符
items[i].namn[sizeof(items[0].namn) - 1] = '\0'; // 手动添加字符串终止符,避免strncpy不自动加的问题

因为strncpy如果复制长度达到上限,不会自动添加'\0',所以手动添加终止符能保证字符串是合法的。


内容的提问来源于stack exchange,提问作者emano12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:05:35