user3507072
user3507072

Reputation: 287

Append to the list in c

What is the correct way to append to a list in c? Ive been searching everywhere and everytime I try it myself I fail.

typedef struct node
{
    char* groupName;
    int groupSize;
    boolean status;
    struct node* next;
} node;

void add(struct node * *head)
{
    struct node* temp=(struct node *)malloc(sizeof(node));
    temp->groupName=name;
    temp->groupSize=size;

      if ((*head) == NULL) {
          (*head) = temp;
          (*head)->next = NULL;
      } else {
            struct node* ptr = (*head);  //dont change head pointer, so make variable to keep track

            while (ptr != NULL) ptr= ptr->next; //go until the end of the list

            (ptr->next) = temp; //add this new data to the end of the list
            temp->next = NULL; //null becomes end of list
      }
}

call (in main():

add(&head);

Upvotes: 1

Views: 23382

Answers (1)

soulcheck
soulcheck

Reputation: 36767

The problem probably lies in this line of code:

   while(ptr!=NULL) ptr= ptr->next; //go until the end of the list

You change ptr until it's equal to NULL, which most definitely isn't what you want, since you dereference ptr right after the loop.

Change it to

   while(ptr->next != NULL) ptr = ptr->next;

and see if that works. Remember: you are interested in the node that doesn't yet have the next node (so you can insert it).

Upvotes: 4

Related Questions