问题描述
所以我要在一个单独的函数中创建一个链表,当我在函数中打印出链表时,似乎一切都很好.然而;当我进入main并尝试使用printf访问链表时,出现了分段错误,并且很困惑为什么.
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);
推荐答案
在C函数中,所有参数均按值传递.因此,如果要更改函数中的变量,则需要传递该变量的地址并在函数中取消引用参数.
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.
此外,您没有为节点分配正确的空间量.您要的是sizeof(struct node)
,而不是sizeof(struct node *)
.
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);
}
这篇关于创建链接列表,而不传递回Main的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!