I have implemented a short linked list code to add to the beginning of the list.
However the head always contained NULL. I really couldn’t get why its behaving in this way. Any help is appreciated ! Below is the code :
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int iData;
struct node *next;
} Node;
void add2Beg(Node* head, int num);
int main(int argc, char const *argv[])
{
Node *head = NULL;
add2Beg(head, 5);
if (head == NULL)
printf("nothing in head !!!\n");
else{
printf("not null\n");
}
add2Beg(head, 15);
return 0;
}
//adds to the beginning of the linked list
void add2Beg(Node* head, int num)
{
//create a temporary location to hold the new entry
Node* temp = (Node *)malloc(sizeof(Node));
temp->iData = num;
if(head == NULL)
{
head = temp;
printf("inside add2Beg\n");
printf("%d\n", head->iData);
head->next = NULL;
printf("exiting add2Beg\n");
}
else
{
temp->next = head;
printf("%p\n", temp->next);
head = temp;
}
}
Because you never assigned head to anything other than NULL…
here in your function you pass in a copy of “head”
At this point you assign temp to it, so within the scope of this function it’s something vaid, but once you leave this function it’s back to NULL.
You passed in a copy of the pointer “head” and called it “head”. You need to either return the value and assign it in
main()or pass a pointer to head into this function in order for the value to be updated.Solutions:
OR