问题
So I am creating a linked list in a separate function, and when I print out the linked list within the function, it seems everything is fine. However; when I go to main and try to access the linked list with printf I get a segmentation fault and am confused exactly why.
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);
回答1:
In C functions pass all parameters by value. So if you want to change a variable in a function, you need to pass the address of that variable and dereference the parameter in the function.
Also, you're not allocating the right amount of space for your node. You want sizeof(struct node), not 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);
}
来源:https://stackoverflow.com/questions/35350749/creating-linked-list-not-passing-back-to-main