所以我在一个单独的函数中创建一个链表,当我打印出函数中的链表时,似乎一切都很好。然而;当我去主要并尝试使用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);
答案 0 :(得分:2)
在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);
}