【发布时间】:2020-08-14 06:18:09
【问题描述】:
好的,所以对于我的家庭作业,我有一个从文件输入创建链接列表的函数,它就像一个日历,所以它从文件中读取日期和标题。我正在使用一个全局声明的头节点来实现它
更容易使用其他功能。
这是我的节点结构:
typedef struct event_t{
char title[20];
event_date_t date;
struct event_t *next;
}event_t;
event_date_t 只是一个简单的日期结构 函数如下:
void insert_events_linked_list(FILE *file, int n){
//printf("LL function started\n"); //self-explanatory test line
event_t last;
head.next = &last;
int i;
//This loop will create a ll of the specified length
for(i=0; i<n; i++){
event_t *last = malloc(sizeof(event_t));
int title_test = fscanf(file, "%20s%*c", last->title);
printf("%s\n", last->title); //test line to make sure names are grabbed properly
//This skips the rest of the event and prints error message if title is too long
if(title_test != 1){
fscanf(file, "%*s %*d %*d");
printf("Error: LL event %d title too long\n", i++);
continue;
}
else{
fscanf(file, "%d %d", &last->date.month, &last->date.day);
last = last->next;
}
}
printf("Loop exited");
}
测试行打印所有标题,但在打印“循环退出”之前显示分段错误并中止
【问题讨论】:
-
当你使用你的调试器时,它说哪一行发生了段错误?
-
顺便说一句,
head.next = &last;会以糟糕的方式结束。head是全局变量,而last是局部变量。 -
@Joseph Sible-Reinstate Monica 看起来它正在循环结束后立即发生,有没有办法做一个全局链表?这将使它更容易使用,因为我最终需要使用其他几个函数对这个列表进行更多操作。
-
关闭 1。使用
char title[20]; ....fscanf(file, "%19s%*c", last->title);/ 发布示例输入。
标签: c linked-list segmentation-fault