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

C语言调用qsort对结构体指针数组排序结果错误问题求助

问题根因

你要排序的是struct hotel *类型的指针数组,qsort传递给比较函数的参数是指向数组元素的指针,也就是传入roomcomp的p1、p2实际是struct hotel **类型。你直接将其强转为struct hotel *,相当于把指针变量本身的存储值当做结构体的内存地址去读取字段,自然会得到错误的比较结果。

修复方案

修改两个比较函数的类型转换逻辑,先解引用一次拿到实际的struct hotel *结构体指针,再访问对应字段即可:

/* 按nrooms升序排列的比较函数 */
int roomcomp(const void *p1, const void *p2)
{
    const struct hotel *h1 = *(const struct hotel **)p1;
    const struct hotel *h2 = *(const struct hotel **)p2;
    return h1->nrooms - h2->nrooms;
}

/* 按地址字典序排列的比较函数 */
int addcomp(const void *p1, const void *p2)
{
    const struct hotel *h1 = *(const struct hotel **)p1;
    const struct hotel *h2 = *(const struct hotel **)p2;
    return strcmp(h1->address, h2->address);
}

补充说明:代码中使用malloc和strdup申请的内存使用完成后需要手动释放,避免产生内存泄漏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:15:10