我是C新手,并尝试学习如何在链接列表上实现C.我很困惑为什么我不能在主函数中访问myList?因为当我尝试myList->data
时,这是分段错误。我认为我的addtohead函数有一些错误? 下面是我的代码:使用C链接列表中的分段错误使用C
#include <stdio.h>
#include <stdlib.h>
typedef struct NODE{
int data;
struct NODE *next;
}node;
node * myList;
node * addToHead(node*, int);
void printList();
int main(){
myList = NULL;
int input;
while (scanf("%i",&input) == 1){
addToHead(myList, input);
printf("%d \n", myList->data);
}
printf("My List:\n");
printList(myList);
return 0;
}
node* addToHead(node* head, int newData){
node *temp = (node *)malloc(sizeof(node));
temp -> data = newData;
temp -> next = NULL;
if(head != NULL){
temp -> next = head;
}
head = temp;
return head;
}
void printList(node* head){
node *temp = head;
while(temp != NULL){
printf("%d ", temp->data);
temp = temp -> next;
}
printf("\n");
}
你没有做什么用函数的返回值。参数'head'是main中的一个副本*。试试'myList = addToHead(myList,input);'。 –
将'head'变成'addToHead'具有本地范围。 – LPs