【发布时间】:2016-08-30 13:34:17
【问题描述】:
我是 C 的新手,并尝试学习如何在链表上实现 C。我真的很困惑为什么我不能在主函数中访问 myList ?因为当我尝试myList->data 时,这是分段错误。我认为我的 addtohead 函数有一些错误?
以下是我的代码:
#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是主参数的副本。试试myList = addToHead(myList, input);。 -
headintoaddToHead具有本地范围。
标签: c linked-list singly-linked-list