所以我在一个单独的函数中创建一个链接列表,当我在函数中打印出链接列表时,似乎一切都很好。然而;当我进入 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);
最佳答案
在 C 函数中按值传递所有参数。因此,如果要更改函数中的变量,则需要传递该变量的地址并取消引用函数中的参数。
此外,您没有为节点分配正确的空间量。您需要 sizeof(struct node)
,而不是 sizeof(struct node *)
。
void createLL(struct node **head, struct node **curr, char ch, int number){
//lowest digit is the head
while (((scanf(" %c",&ch)) >= 0)){
// don't cast the return value of malloc
*curr = 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);
}
关于创建链表,不传回Main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35350749/