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

C语言如何在resultats结构体内部实现动态titre结构体数组的增删操作

问题修复方案

原有代码核心问题

  • 新增元素后未对计数字段nb_titre执行自增,后续新增会覆盖已有元素
  • 直接用原指针接收realloc返回值,分配失败时会丢失原有内存地址造成泄漏
  • 分支逻辑冗余,realloc天然支持NULL指针作为入参,无需单独处理空数组场景
  • 仅复制了tconst字段,未同步start_year字段,存入的数据不完整
  • 缺失内存分配结果校验,分配失败时后续操作会触发空指针崩溃

修正后的完整代码

struct titre {
    char* tconst;
    int start_year;
};

typedef struct titre* t_titre;

struct resultats {
    int nb_titre;
    t_titre *tab_titre;
};

typedef struct resultats* t_resultats;

// 创建空的resultats结构体
t_resultats creer_resultats(void) {
    t_resultats resultats_temp = malloc(sizeof(struct resultats));
    assert(resultats_temp);
    resultats_temp->nb_titre = 0;
    resultats_temp->tab_titre = NULL;
    return resultats_temp;
}

void add_title_to_result(const t_titre titre_temp, t_resultats resultats) {
    // 先扩展数组空间,用临时指针接收realloc返回值避免内存泄漏
    t_titre *new_tab = realloc(resultats->tab_titre, (resultats->nb_titre + 1) * sizeof(t_titre));
    // 分配失败直接终止,也可根据业务需求调整错误处理逻辑
    assert(new_tab != NULL);
    
    resultats->tab_titre = new_tab;
    // 为新的titre结构体分配空间
    t_titre new_titre = malloc(sizeof(struct titre));
    assert(new_titre != NULL);
    
    // 复制titre的两个字段,注意如果tconst是动态字符串,set_tconst要做深拷贝
    set_tconst(new_titre, titre_temp->tconst);
    new_titre->start_year = titre_temp->start_year;
    
    // 存入数组,计数自增
    resultats->tab_titre[resultats->nb_titre] = new_titre;
    resultats->nb_titre++;
}

额外注意事项

  • 如果需要实现删除逻辑,删除指定下标元素时要先调用free释放对应tab_titre[i]的内存,再将后续元素向前移动,最后调用realloc缩容数组即可
  • set_tconst函数内部要对tconst做深拷贝(申请新内存复制字符串内容),不要直接赋值指针,否则原tconst内存被释放后,结构体里的指针会变成野指针
  • 整个resultats使用完后要先遍历释放所有tab_titre元素的内存,再释放tab_titre本身,最后释放resultats结构体,避免内存泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:24:06