我正在创建一个简单的链表程序来插入和查看LL的元素。当我试图插入第二个元素时,它给出了SIGSEV,但我不明白为什么??!!
请帮我指出问题:
main.c:
#include <stdio.h>
#include <stdlib.h>
typedef struct linkedList{
int data;
struct linkedList *next;
}LL;
LL *start;
int main(){
int option = 0;
while(1){
printf("Enter option: n");
scanf("%d", &option);
switch(option){
case 1:
addNode(start);
break;
case 2:
readNodes(start);
break;
case 3:
exit(0);
}
}
}
插入节点:
int addNode(LL *startNode){
LL *temp, *node;
int data = 0;
printf("Enter data: ");
scanf("%d", &data);
if(startNode == NULL){/*Application only when the first element is inserted*/
startNode = (LL*)malloc(sizeof(LL*));
if(startNode == NULL){
printf("Error: Memory not allocated!!n");
exit(1);
}
startNode->data = data;
startNode->next = NULL;
start = startNode;
return 0;
}
temp = startNode;
while(temp != NULL){
temp = temp->next;
}
node = (LL*)malloc(sizeof(LL*));
node->data = data;
node->next = NULL;
temp->next = node;
temp = temp->next;
return 0;
}
sizeof
占用结构的长度,对于32位体系结构,您总是传递4个字节- 迭代
temp
节点的while循环是错误的,您应该检查next
节点是否为NULL