user3807640
user3807640

Reputation: 3

insert an element at end node of link list in c

i want to add a node at end of link list. so i made a method for the same and it gives expected result. But i am not sure about this program is correct or not. please see program wether it is correct or not.

node *insert_end_node(node *nd, int value) {
  node *tmp, *p;

  tmp = (node *)malloc(sizeof(node *));

  tmp->data = value;
  tmp->next = NULL;
  p = nd;
  while (p->next != NULL) {
    p = p->next;
  }

  p->next = tmp;

  // nd =tmp;

  return nd;
}

Thanks in advance

Upvotes: 0

Views: 125

Answers (1)

Daniel Kleinstein
Daniel Kleinstein

Reputation: 5502

Two things:

  1. When you accept a pointer as a parameter, you should always check to see if it is NULL. In your case, if nd == NULL, then you will try to access NULL->next and your program will likely crash.
  2. When you call tmp = (node *)malloc(sizeof(node*)), you want to allocate enough memory for a node, not for a node pointer. The correct code is tmp = (node *)malloc(sizeof(node)). An even better option is to write tmp = (node *)malloc(sizeof(*tmp)), because if you decide to change tmp's type, the allocation will still work.

Upvotes: 1

Related Questions