I started writing this very simple function in C to add node to a singly link list at the head. Here is my function. head
parameter is pointer to the first node of the linked list. It can come as NULL
if linked list is empty. data
is the number to be put in data field of the new node to be added:
Node* InsertAtHead(Node *head, int data)
{
Node newHeadNode;
newHeadNode.data = data;
newHeadNode.next = NULL;
if (head == NULL)
{
head = &newHeadNode;
}
else
{
newHeadNode.next = head;
head = &newHeadNode;
}
return head;
}
Definition of Head is as below:
struct Node
{
int data;
struct Node *next;
};
This works on my machine but not on my colleague's machine. At the other machine the program gives segmentation fault error. What is wrong in my function?
newHeadNode
? – SMAnewHeadNode
will get allocated on stack since it is local to the function but will get lost once function scope is gone. – RBTNode* ..
won't compile! it should bestruct Node* ..
unless there is atypedef
you are not showing in the question. – ThunderWiringNode
, there isstruct Node
however. – ThunderWiring