[英]accessing nodes of linked list using double pointers
I am trying to add nodes in a linked list, passing the pointer of pointer, accessing the member (*list) -> next gives a segmentation fault. 我试图在链表中添加节点,传递指针的指针,访问成员(* list)->接下来给出分段错误。 Can someone point out the mistake, thanks in advance. 有人可以指出错误,在此先感谢。 The code is 该代码是
void initializeList (node ** head, int data)
{
*head = malloc (sizeof (node));
(*head)-> member = data;
(*head)-> next = NULL;
}
void addNode(node ** list, int data)
{
node * newNode = NULL;
newNode = malloc (sizeof (node));
while (*list->next!= NULL)
{
*list= (*list) -> next;
}
newNode -> member = data;
newNode -> next = NULL;
(*list) -> next = newNode;
}
void main ()
{
node * head = NULL;
initializeList (&head, 5);
addNode(&head, 6);
}
You should not dereference a NULL pointer, otherwise as expected you get Seg Fault. 您不应该取消引用NULL指针,否则会出现Seg Fault错误。
Here's the problem: 这是问题所在:
while (*list != NULL)
{
*list= (*list) -> next;
}
newNode -> member = data;
newNode -> next = NULL;
(*list) -> next = newNode;
*list
is NULL after while loop. while循环后, *list
为NULL。
And you are doing (*list) -> next = newNode;
而您正在(*list) -> next = newNode;
newNode points to NULL after the loop You cannot set its member and next value use while(*list->next!= NULL) 循环后newNode指向NULL不能使用while(* list-> next!= NULL)设置其成员和下一个值
which ensures that you are not dereferencing NULL 这可以确保您不取消引用NULL
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.