我正在尝试从文本文件中读取数字并创建一个双向链表。我对双向链表的工作原理有很好的理解,但我在应用程序上遇到了困难。我知道我可能正在尝试取消引用 NULL 指针或指向范围之外。但是,我似乎无法弄清楚具体在哪里。
它输出第一个数字,然后在 if
/else
语句的某处给出一个段错误。
#include<stdio.h>
#include<stdlib.h>
struct node {
int val;
struct node *next;
struct node *prev;
};
struct list {
struct node *head;
struct node *tail;
};
int main()
{
struct node *temp = NULL;
struct list *l = NULL;
FILE *fileptr;
char filename[20], num[3];
printf("Enter filename: ");
scanf("%s", filename);
fileptr = fopen (filename, "r");
while(fscanf(fileptr, "%s", num) != EOF)
{
printf("Number is: %d\n", atoi(num));
temp = (struct node *) malloc(sizeof(struct node));
printf("HELLO 1\n");
temp->val = atoi(num);
printf("HELLO 2\n");
if(l->tail == NULL)
{
l->head = temp;
l->tail = temp;
}
else
{
l->tail->next = temp;
temp->prev = l->tail;
l->tail = temp;
}
}
return 0;
}
最佳答案
结构列表 *l = NULL;是错误的,因为您没有为 l 分配任何内存
你可以这样做
struct list *l = ( struct list *)malloc(sizeof(struct list));
l->head = NULL;
l->tail = NULL;
或者你可以尝试
struct list l = {0}; and later use l.head or l.tail
关于c - 创建双向链表时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37647562/