#include <stdio.h>
#include <stdlib.h>
#include "list.h"
void listInsertHead (List l, int val) {
Node start;
start = calloc(1, sizeof(node));
start->value = val;
start->next = l->head;
l->head = start;
Node current;
while (current != NULL) {
printf("data is %d\n", current->value);
current = current->next;
}
}
int main(int argc, char *argv[]) {
List new = calloc(1, sizeof(list));
Node first = calloc(1, sizeof(node));
Node second = calloc(1, sizeof(node));
Node third = calloc(1, sizeof(node));
first->value = 10;
new->head = first;
second->value = 20;
third->value = 30;
first->next = second;
second->next= third;
third->next = NULL;
listInsertHead(new, 5);
return 0;
}
typedef struct _node *Node;
typedef struct _list *List;
typedef struct _list {
Node head;
} list;
typedef struct _node {
int value;
Node next;
} node;
我尝试将新节点添加到链接列表的开头作为头部。但是,我一直在分段错误,所以我不确定该怎么做。结构位于代码的底部。所以我试图做的是:
1→2→3→NULL
新的(节点) - &GT; 1→2→3→NULL
答案 0 :(得分:3)
您的segfault来自于尝试打印列表而未初始化current
变量:
Node current;
while (current != NULL) {
printf("data is %d\n", current->value);
current = current->next;
}
你还没有将它设置为任何东西,但正试图循环它 - 你需要初始化它:
Node current = l->head;