Aaron Hiller Aaron Hiller - 28 days ago 7
C Question

c - double pointers to add to tail of linked list

void insertAtTail( List *list, int val )
{
//double pointer to head
Node **link = &( list->head );
//move to end of list
while(*link != NULL) {
*link = (*link)->next;
}
//create new node
Node *n = (Node *)malloc(sizeof(Node));
n->value = val;
n->next = NULL;
//insert node at end
*link = n;


This code is supposed to add a value from the input file to the end of the list(to reverse the list) but my output is just
29
with a segmentation fault. It seems to be just overwriting each value added then writing past the end of the list. How could I insert each value to the end of the list without overwriting each value? The input follows:

72 19 47 31 8 36 12 88 15 75 51 29

Answer

Assuming you want to use a double pointer, you just need to fix one line (noted with a comment):

void insertAtTail( List *list, int val )
{
  //double pointer to head
  Node **link = &( list->head );
  //move to end of list
  while(*link != NULL) {
    link = &(*link)->next;      // this line fixed
  }
  //create new node
  Node *n = (Node *)malloc(sizeof(Node));
  n->value = val;
  n->next = NULL;
  //insert node at end
  *link = n;
}

Microsoft compilers for C require that variables be declared at the start of a function, minor change noted in comment:

void insertAtTail( List *list, int val )
{
    //double pointer to head
    Node **link = &( list->head );
    Node *n;                        // moved declaration
    //move to end of list
    while(*link != NULL) {
        link = &(*link)->next;      // this line fixed
    }
    //create new node
    n = (Node *)malloc(sizeof(Node));
    n->value = val;
    n->next = NULL;
    //insert node at end
    *link = n;
}
Comments