【问题标题】:Dynamically allocate array in struct - c在struct-c中动态分配数组
【发布时间】:2013-12-14 21:49:37
【问题描述】:

尝试从 csv 文件动态分配数据。我正在尝试制作一个包含二维数组的结构数组。问题是我在尝试为结构内的数组分配内存时遇到访问冲突。用评论标记问题区域。任何帮助表示赞赏。

 typedef struct current{

    char **data;

}*CurrentData;

CurrentData getData(FILE *current){

CurrentData *AllCurrentData = malloc(NUM_ITEMS * sizeof(CurrentData));

    /*allocate struct data memory, skipping the first line of data*/
    while ((ch = fgetc(current)) != EOF){
        if (firstNewLine == 0){
            firstNewLine++;
        }
        if (firstNewLine > 0){
            if (ch == '\n'){
                AllCurrentData[newLineCount]->data = malloc(COLUMNS * sizeof(char));  //problem here//
                newLineCount++;
            }
        }
    }
}

【问题讨论】:

  • newLineCount在哪里初始化为0?
  • @OldProgrammer 没有main,所以我认为他只是显示了“重要”代码。

标签: c memory dynamic allocation


【解决方案1】:

下面这行:

CurrentData *AllCurrentData = malloc(NUM_ITEMS * sizeof(CurrentData));

应该是:

CurrentData AllCurrentData = malloc(NUM_ITEMS * sizeof(*CurrentData));

也替换这个:

AllCurrentData[newLineCount]->data

用这个:

AllCurrentData[newLineCount].data

原因:你有typedefed CurrentData 是指向struct current 的指针,你可以直接将AllCurrentData 分配为struct current 的数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-30
    • 2016-09-29
    • 2014-02-13
    • 2019-12-28
    相关资源
    最近更新 更多