【问题标题】:Why is this simple linked list program giving segmentation fault?为什么这个简单的链表程序会出现分段错误?
【发布时间】:2015-02-01 15:09:35
【问题描述】:

我只是想创建一个字符的链接列表。代码如下:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

struct node{
    char data;
    struct node *next;
};

void push(struct node** head,char ndata)
{
    struct node* temp=(struct node*)malloc(sizeof(node));
    temp->data=ndata;
    temp->next=(*head);
    *head=temp;
}

void display(struct node* head)
{
    struct node* temp=head;

    while(temp)
    {
        printf("%c ",temp->data);
        temp=temp->next;
    }   
}

int main()
{
    struct node* head;
    int a=1;
    push(&head,'a');
    push(&head,'b');
    push(&head,'c');
    push(&head,'b');
    push(&head,'a');

    display(head);  
    getch();
    return 0;
}

我正在使用 push() 函数,它在头部插入值。然后使用 display() 方法显示列表中的值。当我执行程序时, 它说“program10.exe 已停止工作”。 我不明白问题是什么。有人可以帮忙吗?

【问题讨论】:

  • sizeof(node) ?没有typedef?怎么样??
  • 我正在使用 Dev-CPP 编译器。它会自动“附加” typedef。

标签: c linked-list segmentation-fault


【解决方案1】:

您没有初始化head,所以它不为空但有一个垃圾值,所以它不会停止display函数中的循环,并尝试在那里取消引用垃圾。

这个:

struct node* head;

应该是:

struct node* head = NULL;

【讨论】:

  • 该死的。我怎么错过了?谢谢老兄。
猜你喜欢
  • 2019-04-17
  • 1970-01-01
  • 1970-01-01
  • 2014-03-31
  • 1970-01-01
  • 2015-04-23
  • 2021-02-05
相关资源
最近更新 更多