所以我在一个单独的函数中创建了一个链表,当我在函数中打印出链表时,似乎一切都很好。然而;当我转到 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("%dn",curr->data);
curr = curr->next;
}
curr = head;
printf("%dn",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("%dn",currOne->data);
createLL(headTwo,currTwo, ch, number);
printf("%dn",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("%dn",(*curr)->data);
*curr = (*curr)->next;
}
*curr = *head;
printf("%dn",(*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("%dn",currOne->data);
createLL(&headTwo,&currTwo, ch, number);
printf("%dn",currTwo->data);
}