因此,我在一个单独的函数中创建链接列表,并且当我打印出函数中的链接列表时,似乎一切正常。然而;当我转到main并尝试使用printf访问链接列表时,我得到了一个分段错误,我很困惑,为什么。创建链接列表,不传回主
void createLL(struct node* head, struct node* curr, char ch, int number){
//lowest digit is the head
while (((scanf(" %c",&ch)) >= 0)){
curr = (struct node*)malloc(sizeof(struct node*)); //allocate space
number = ch - '0' ; //convert char to number
curr->data = number;
curr->next = head;
head = curr;
}
curr = head;
//troubleshoot
while(curr){
printf("%d\n",curr->data);
curr = curr->next;
}
curr = head;
printf("%d\n",curr->data);
}
int main(){
//initials
int i, number;
char ch;
//node pointers
struct node* headOne = NULL;
struct node* currOne = NULL;
struct node* headTwo = NULL;
struct node* currTwo = NULL;
//create linked list
createLL(headOne,currOne, ch, number);
printf("%d\n",currOne->data);
createLL(headTwo,currTwo, ch, number);
printf("%d\n",currTwo->data);
'createLL(headOne,currOne,ch,number);'这是行不通的:它不可能改变'headOne',它将永远是NULL。 –
扩展Martin评论,您需要将指针传递给createLL中的指针,以便您可以修改例程中在main中声明的列表。也就是说,createLL的签名应该是这样的:void createLL(struct node ** head,struct node ** curr,char ch,int number) – Harald
另外请注意,在SO上发布的大约一半的LL问题有这个问题,并且有很多。 –