[英]accessing nodes of linked list using double pointers
我試圖在鏈表中添加節點,傳遞指針的指針,訪問成員(* 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.