我將使用strtok
讀取兩組char*
(或字符串),並且由於這兩組字符是相關的,所以我決定使用一個結構。如何正確malloc爲C的結構數組
struct line* array = (struct line*)malloc(sizeof(file) * sizeof(struct line*));
此行malloc
的功能ING空間給了我一個分段錯誤,並想知道如果你能以適當的方式告訴我吧malloc
空間。對於上下文,這是我的代碼的其餘部分:
struct line
{
char* addr;
char* inst;
};
while loop{
x = strtok(line,": ");
y = strtok(NULL,"\n");
strcpy(array[i].addr,x); //assume that x and y are always 3characters
strcpy(array[i].inst,++y);
i++;
}
請介意爲'struct line'數組分配內存不會爲'addr'和'inst'字符串分配內存。根據如何使用'struct line'內的指針,你可能還需要爲字符串數據分配內存。 –