首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在C中打印反向链接列表时分割错误(内核转储)

在C中打印反向链接列表时分割错误(内核转储)
EN

Stack Overflow用户
提问于 2021-11-22 04:02:41
回答 2查看 114关注 0票数 0

我试图反转这个链接列表,但是在输入之后,它给出输出分段错误(核心转储),同时打印列表。这只发生在我声明第4指针之前,它运行良好时,只有三个指针头部,新代码,临时。

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h>

int main()
    {
        struct node
        {
            int data;
            struct node *next;
        };

    struct node *head, *newnode, *temp;
    int choice = 1;

    // Creating a linked-list
    while (choice)
    {
        newnode = (struct node *)malloc(sizeof(struct node));
        printf("Enter the data: ");
        scanf("%d", &newnode->data);
        newnode->next = 0;
        if (head == 0)
        {
            head = temp = newnode;
        }
        else
        {
            temp->next = newnode;
            temp = newnode;
        }
        printf("Do you want to continue: ");
        scanf("%d", &choice);
    }
    temp = head;

    // Reversing the LL
    struct node *prevnode, *currentnode, *nextnode;
    prevnode = 0;
    currentnode = nextnode = head;
    while (nextnode != 0)
    {
        nextnode = nextnode->next;
        currentnode->next = prevnode;
        prevnode = currentnode;
        currentnode = nextnode;
    }
    head = prevnode;

    // Printing the Linked-list
    while (prevnode != 0)
    {
        printf("%d ", prevnode->data);
        prevnode = prevnode->next;
    }
    return 0;
}

据我所知,分割错误仍然无法判断到底是哪一部分造成了错误。

EN

回答 2

Stack Overflow用户

发布于 2021-11-22 04:19:30

您需要将head初始化为0。默认情况下不初始化指针。否则,它就能正常工作。

票数 1
EN

Stack Overflow用户

发布于 2021-11-22 04:34:56

head未初始化,因为指针在默认情况下未初始化

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70060775

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档