Reputation: 3
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
Reputation: 5502
Two things:
nd == NULL
, then you will try to access NULL->next
and your program will likely crash.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