我正在尝试在链表中添加节点,传递指针的指针,访问成员(*list)->接下来会出现分段错误。有人能指出错误吗,提前谢谢。代码是
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);
}
您不应该取消引用NULL指针,否则会出现Seg Fault。
问题是:
while (*list != NULL)
{
*list= (*list) -> next;
}
newNode -> member = data;
newNode -> next = NULL;
(*list) -> next = newNode;
while循环后*list
为NULL
您正在执行(*list) -> next = newNode;
newNode在循环后指向NULL不能设置其成员和下一个值使用while(*list->next!=NULL)
这可以确保您不会取消引用NULL