【发布时间】:2018-04-11 15:00:09
【问题描述】:
我正在尝试创建一个结构数组,并且正在从 .txt 文件中读取结构的元素。当我尝试从文件中扫描字符串时,我的程序停止并且在调试代码块时显示“程序收到信号 SIGSEGV,分段错误。”。我正在尝试从文件中读取字符串并将它们分配给我的结构。我该怎么办?
我的 .txt 文件如下:
H 1 1 MILK White liquid produced by the mammals
H 2 1 IN Used to indicate inclusion within space, a place, or limits
H 3 3 BUS A road vehicle designed to carry many passengers
H 5 3 DAN The name of a famous author whose surname is Brown
V 1 1 MIND A set of cognitive faculties, e.g. consciousness, perception, etc.
V 3 3 BAD Opposite of good
V 2 5 ISBN International Standard Book Number
我的 loadTextFile 函数将这些值分配给我的结构数组如下:
Word_t* loadTextFile(FILE* myfile, int nrWords)
{
Word_t* temp;
temp=malloc(sizeof(Word_t)*nrWords);
temp->word=malloc(MAX_WORD_LENGTH);
temp->clues=malloc(MAX_CLUES_LENGTH);
for(int count=0;count<nrWords;count++)
{
fscanf(myfile," %c %d %d %s %[^\n]%*c", &temp[count].direction,&temp[count].x, &temp[count].y, temp[count].word, temp[count].clues);
}
printf("ELEMENTS");
for(int i=0;i<nrWords;i++)
{
printf("%c %d %d %s %s\n", temp[i].direction, temp[i].x, temp[i].y,temp[i].word, temp[i].clues);
}
return temp;
}
我想让我的输出看起来像 txt 文件。
【问题讨论】:
-
“我应该怎么做?” 了解如何使用调试器来诊断基本的基本问题,例如段错误,而不是浪费您和其他人的时间要求其他人这样做给你。