簡體   English   中英

在結構中動態分配數組-C

[英]Dynamically allocate array in struct - c

嘗試從csv文件動態分配數據。 我正在嘗試制作包含2d數組的結構數組。 問題是,嘗試為結構內的數組分配內存時遇到訪問沖突。 用注釋標記問題區域。 任何幫助表示贊賞。

 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++;
            }
        }
    }
}

以下行:

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

應該:

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

還可以替換為:

AllCurrentData[newLineCount]->data

有了這個:

AllCurrentData[newLineCount].data

原因:你擁有了typedefCurrentData是一個指針struct current ,你可以直接分配AllCurrentData作為陣列struct current

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM