【发布时间】:2016-05-22 21:40:28
【问题描述】:
所以我在一个单独的函数中创建了一个链表,当我在函数中打印出链表时,似乎一切都很好。然而;当我转到 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);
【问题讨论】:
-
'createLL(headOne,currOne, ch, number);'那是行不通的:它不可能改变'headOne',它将永远为NULL。
-
扩展 Martin 注释,您需要将指针传递给 createLL 中的指针,以便您可以在例程中修改 main 中声明的列表。也就是说,createLL 的签名类似于: void createLL(struct node ** head, struct node** curr, char ch, int number)
-
另外,请注意,在 SO 上发布的 LL 问题中约有一半存在这个问题,而且还有很多。
-
双星的替代方案:返回头部; 'headOne=createLL(headOne,currOne, ch, number);'
-
叹息!
void函数,但通过参数“返回”一个值... tssssss
标签: c pointers linked-list