C++ Struct Pointer Segfault

后端 未结 1 1019
醉梦人生
醉梦人生 2021-01-25 15:51

First, thanks in advance for all of you who respond to this post.

Second, I\'ve looked through all other posts and couldn\'t find anything that helped me (my apologies,

相关标签:
1条回答
  • 2021-01-25 16:35

    The most likely issue here is that you cannot use Insert to "jump start" your list: if the head is NULL to start with, the loop is going to fail right away. Moreover, on the first insertion you wouldn't be able to assign the head.

    To fix this problem, change the first parameter from Node *head to Node **pHead, pass a pointer to the head pointer, and add an extra level of dereference to the code of your Insert function:

    Node* Insert(Node **pHead, int data)
    {
        while(*pHead != NULL){
            pHead = &((*pHead)->next);
        }
        Node *last = new Node();
        last -> data = data;
        last -> next = NULL;
        *pHead = last;
        return last;
    }
    

    Note that this approach is going to work even if you pass a pointer to Node pointer that is set to NULL:

    Node *head = NULL;
    Insert(&head, 1);
    Insert(&head, 2);
    Insert(&head, 3);
    
    0 讨论(0)
提交回复
热议问题