简体   繁体   中英

C++ Struct Pointer Segfault

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, I'm new to C++).

Here's my code:

Node* Insert(Node *head,int data) //for linked lists
{
  Node* current = head;
  while(current -> next != NULL){
      current = current -> next;
  }
  cout << head -> data;
  Node *last = new Node();
  last -> data = data;
  last -> next = NULL;
  current -> next = last;
  return head;
}

It seems (by trial and error of line commenting) that the access of the next attribute in the current pointer seems to be the problem, yet I can't seem to figure out why. The Node struct has two attributes, *next (which points to the next item in the linked list) and data (the data of the node).

Any ideas of what's going on?

linuxuser

EDIT: The problem was solved - thanks so much to all who left comments!

Sadly, I wasn't able to use the **pHead dereferencing solution, as the problem is on a website that auto-inputs the arguments for the function. Using the comments below, however, I made a simple program that I hope will detail this issue for other beginning C++ programmers like me:

Node* Insert(Node *head,int data)
{
    if(head == NULL){
        Node* last = new Node();
        last -> data = data;
        return last;
    }

    Node *current = head;
    while(current -> next != NULL){
        current = current -> next;
    }
    Node *last = new Node();
    last -> data = data;
    last -> next = NULL;
    current -> next = last;
    return head;  
}

Regards,

linuxuser

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM