c - 创建双向链表时出现段错误

标签 c

我正在尝试从文本文件中读取数字并创建一个双向链表。我对双向链表的工作原理有很好的理解,但我在应用程序上遇到了困难。我知道我可能正在尝试取消引用 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/

相关文章:

c++ - 为什么我需要将 lib 文件链接到我的项目?

c - 未决请求队列存储在哪里?

c - 结构访问代表文件名?

c - scanf 不输入空格作为字符

c - 将指定内容放入c中的缓冲区

c - 为什么在 realloc 函数中使用它之前 NULL ing 指针?

c - 当我们将 "if(ptr==NULL)"用作整数指针 ptr 时,NULL 指针是否隐式转换为类型 (int*)?

arrays - 修复char格式错误-Linux系统C程序

c - 使用 strcpy 和 strcat 时堆栈粉碎

c - <stdlib.h> rand() 示例代码,对大于最大值的不必要检查?