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

C语言结构体嵌套时内部结构体数组malloc分配后值无法存储问题

问题代码存在的错误点

  • 结构体定义顺序错误:Airport 结构体需要定义在 AirportManager 之前,否则 AirportManager 中声明的 Airport* 类型会无法识别
  • 初始化函数内存分配错误:initAirportManager 中给 airportArray 分配内存时强制转换类型写为了 AirportManager*,与实际的 Airport* 类型不符,且不需要调用malloc(0),直接初始化为NULL即可(realloc支持传入空指针)
  • 初始化函数传参错误:main中调用initAirportManager时需要传入结构体指针,你传入的是结构体值,会导致修改无法生效
  • 数组赋值逻辑错误:addAirport最后直接把Airport结构体赋值给了数组首指针airportArray,而不是赋值给新扩展的数组元素,导致指针地址被篡改,数据无法存储
  • 额外优化点:realloc分配内存时建议先接收返回值到临时指针,确认分配成功再赋值给原指针,避免分配失败时原指针丢失导致内存泄漏;scanf读取字符串时建议限制长度,避免缓冲区溢出

修正后完整代码

#include <stdio.h>
#include <stdlib.h>
#define MAX 100 // 可根据实际需求调整MAX的数值

// 先定义Airport结构体
typedef struct {
    char airportName[MAX];
    char airportAddress[MAX];
} Airport;

// 再定义AirportManager结构体
typedef struct {
    Airport* airportArray;
    int airportAmount;
} AirportManager;

void initAirportManager(AirportManager* airportManager) 
{
    airportManager->airportAmount = 0;
    airportManager->airportArray = NULL; // 直接初始化为空即可
}

void addAirport(AirportManager* airportManager)
{
    Airport airport;
    printf("Enter Airport Name: ");
    scanf("%99s", airport.airportName); // 限制读取长度,预留字符串结束符位置
    printf("Enter Airport Address: ");
    scanf("%99s", airport.airportAddress);
    
    airportManager->airportAmount++;
    // 用临时指针接收realloc返回值,避免分配失败丢失原指针
    Airport* temp = (Airport*)realloc(airportManager->airportArray, airportManager->airportAmount * sizeof(Airport));
    if (temp == NULL) {
        perror("内存分配失败");
        airportManager->airportAmount--;
        return;
    }
    airportManager->airportArray = temp;
    // 赋值给数组最后一个新增元素
    airportManager->airportArray[airportManager->airportAmount - 1] = airport;
}

int main()
{
    AirportManager airportManager;
    initAirportManager(&airportManager); // 传入结构体指针
    addAirport(&airportManager);
    // 测试验证写入结果
    printf("已添加机场:%s,地址:%s", 
           airportManager.airportArray[0].airportName, 
           airportManager.airportArray[0].airportAddress);
    // 使用结束后释放堆内存
    free(airportManager.airportArray);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 01:36:01