c - 链表段错误

标签 c linked-list

我遇到了段错误,但我不知道问题出在哪里。

#include "stdio.h"
#include "stdlib.h"

struct node {
    int data;
    struct node *next;
    };
    struct node *head = NULL;
    struct node * curr;
    struct node * newNode;

void createList(){

    int data,n , i ;
    scanf("%d",&n);
    for (i = 0 ; i < n ;i++){
        scanf("%d",&data);
        curr = head;
        newNode = (struct node*)malloc(sizeof(struct node));
        newNode->data=data;
        newNode->next=NULL;
        if ( curr == NULL){
            head = newNode;
        }else
            while (curr->next != NULL){
                curr = curr->next;
            }
            curr->next = newNode;
    }

}

int main(int argc, char const *argv[])
{

    createList();
    return 0;
}

请问你知道在哪里吗? 第一次迭代很好,但是当 i = 1 时,出现错误。

最佳答案

对齐不足以在 C 中生成 block 代码;-)

需要牙套。没有它,语句 curr->next = newNode; 位于 else block 之外,这不是您想要的。

  if ( curr == NULL){
                head = newNode;
   }
   else {
                while (curr->next != NULL){
                    curr = curr->next;
                }
                curr->next = newNode;
   }

关于c - 链表段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30311787/

相关文章:

c - long int 太小

c - 有没有办法在 C 中初始化指向数组的指针(在同一行)

c - 检测到堆栈粉碎错误

c - C 中两个进程共享内存?

c - 用户在 C 中定义类型 PostgreSQL

java - 如何使用链表在java中实现已经很好实现的模块(如堆栈)

c - C 语言字典

c - 计算 int 在列表中出现次数的函数错误

c++ - 遍历链表的列表

java - LinkedList的indexOf()与lastIndexOf()方法优化