[英]Array of structs only outputs last entry read in C
我正在從文件中讀取並將讀取的條目插入到結構中,如下所示:
typedef struct card
{
unsigned int id;
char* name;
char* cost;
unsigned int converted_cost;
char* type;
char* text;
char* stats;
enum rarity rarity;
} card_t;
int main(int argc, char **argv) {
FILE *input_file;
input_file = fopen(argv[1], "r");
card_t **cards = NULL;
int cardsaccum = 0;
char *buf = NULL;
char *name_duplicate;
size_t bufsiz = 0;
ssize_t result = getline(&buf, &bufsiz, input_file);
while (result > 0)
{
// COPIES BUFFER TO SAVE THE MEMORY ADDRESS
char *stringp = buf;
// ALLOCATES MEMORY
cards = realloc(cards, sizeof(card_t *) * num_entries);
cards[cardsaccum] = malloc(sizeof(card_t));
name_duplicate = strsep(&stringp, "\"");;
cards[cardsaccum]->name = name_duplicate;
cardsaccum++;
num_entries++;
result = getline(&buf, &bufsiz, input_file);
}
for(int i = 0; i < cardsaccum; i++)
{
printf("%s\n",cards[i]->name);
}
// FREEING MEMORY
for(i = 0; i < cardsaccum;i++)
{
free(cards[i]);
}
free(cards);
free(buf);
fclose(input_file);
return 0;
}
該文件應讀取 Bob、Marley、Frank 的姓名。 但是,我的 output 只打印最后一個條目:
Frank
Frank
Frank
我對 memory 的分配有問題還是有其他問題? 任何幫助表示贊賞!
function getline()
) 在內部調用realloc()
。 結果,所有先前源自buf
的指針,如strsep(&stringp, "\"")
都將失效或被覆蓋。
請注意,先前的cards[X]->name
指向先前buf
中的某個位置。
在處理下一行之前復制一個字符串:
cards[cardsaccum]->name = strdup(name_duplicate);
其他解決方案是在調用getline
之前將buf
設置回NULL
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.