【问题标题】:Why my stack implementation not working and giving the error "Segmentation fault (core dumped)"为什么我的堆栈实现不工作并给出错误“分段错误(核心转储)”
【发布时间】:2022-11-27 12:45:19
【问题描述】:

为什么我的堆栈实现不工作并给出错误“Segmentation fault (core dumped)” 这是代码 `

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node *next;
};

int main()
{
    struct node *head, *newNode, *temp;
    head = 0;
    int choice=1;
    while(choice)
    {
        
        newNode = (struct node *)malloc(sizeof(struct node));
        printf("Enter Data: \n");
        scanf("%d", &newNode->data);
        newNode->next = 0;
        if (head == 0)
        {
            head=newNode;
        }
        else{
            temp->next=newNode;
            temp=newNode;
        }
        printf("Do You Want to Continue(0,1)?\n");
        scanf("%d",&choice);
        
        }

        temp=head;
        while(temp!=0){
            printf("%d",temp->data);
            temp=temp->next;
    }
    return 0;
}

我试图实现 LInked LIst 但出现错误“分段错误(核心已转储)”

【问题讨论】:

    标签: c


    【解决方案1】:

    在这个 else 语句中

        else{
            temp->next=newNode;
            temp=newNode;
        }
    

    使用了未初始化的指针temo

    你应该写在 if 语句中

        if (head == 0)
        {
            head=newNode;
            temp = head;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-26
      相关资源
      最近更新 更多