首页 文章

继续在此代码上出现seg错误

提问于
浏览
-1

我试图在C中实现一个链表 . 有一个结构列表,其中包含指向列表第一个和最后一个位置的void指针 . 一个struct节点,它有一个指向data的void指针和一个指向next的struct节点指针 . 出于某种原因,当我尝试访问struct list前端指针时,它会出现故障 . 这是代码 . 任何帮助将不胜感激 .

(main方法初始化传递给函数的列表为null)

int main()
{
   struct list *linked_list;
   linked_list = NULL;

   int *ptr;
   int x = 5;
   ptr = &x;

    linked_list = list_add(linked_list,ptr);

 }

struct list {
    void *front;
    void *back;
};

struct node{
    void *data;
    struct node *next;
    struct node *prev;
};

struct list *list_add(struct list *li, void *d){
    struct node *new_node;

    new_node = (struct node *)malloc(sizeof(struct node));
    if(new_node == NULL){
        printf("Malloc failed");
        exit(1);
    }


    new_node->data = d;
    new_node->next = NULL;
    struct node *cur;
    for(cur = li->front; cur != NULL; cur = cur->next){
        if(cur->next == NULL){
            new_node->prev = cur;
        }

    }
    li->front = new_node;
    return li;
}

2 回答

  • 1
    struct list *linked_list;
    linked_list = NULL;
    
    ...
    
    linked_list = list_add(linked_list,ptr);
    

    您正在将NULL指针( linked_list )传递给 list_add() . 然后在 list_add() 中取消引用该指针,导致崩溃 .

    list_add() 内部,在顶部考虑这样的事情:

    struct list *list_add(struct list *li, void *d){
    struct node *new_node;
    
    if (!li) {
        li = malloc(sizeof(*li));
        li->front = li->back = NULL;
    }
    
    new_node = malloc(sizeof(struct node));
    ...
    

    您可能需要做更多的事情,但这会让您超越第一个障碍 . 另请注意,在调用 list_add() 之前,您可以在 main() 中执行类似的初始化 .

  • 0

    首先,我不认为这是做链表的正确方法,不需要列表结构

    int main()
    {
       struct list *linked_list;
       linked_list = NULL;
    
       int *ptr;
       int x = 5;
       ptr = &x;
    
        linked_list = list_add(linked_list,ptr);
    
     }
    
    struct list {
        void *front;
        void *back;
    };
    
    struct node{
        void *data;
        struct node *next;
        struct node *prev;
    };
    
    struct list *list_add(struct list *li, void *d){
        //you need to check if li is null if so initialize it
        if(li ==null){
          li = (struct list*) malloc(sizeof(struct list));
        }
        struct node *new_node;
    
        new_node = (struct node *)malloc(sizeof(struct node));
        if(new_node == NULL){
            printf("Malloc failed");
            exit(1);
        }
    
    
        new_node->data = d;
        new_node->next = NULL;
        struct node *cur;
        for(cur = li->front; cur != NULL; cur = cur->next){
            if(cur->next == NULL){
                new_node->prev = cur;
            }
    
        }
        li->front = new_node;
        return li;
    }
    

    但是不是在函数中检查null,而是将list_add设为void并传入初始化列表

相关问题