[英]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
原因:你擁有了typedef
版CurrentData
是一個指針struct current
,你可以直接分配AllCurrentData
作為陣列struct current
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.