#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
};
struct node* insert_beg(struct node *h,int x)
{
struct node *t;
printf("\n address = %u --- ",*h);
t=(struct node *)malloc(sizeof(struct node));
if(h==NULL)
{
t->data=x;
t->next=NULL;
h=t;
}
else
{
t->data=x;
t->next=h;
h=t;
}
return h;
}
void display(struct node *h1)
{
struct node *t=h1;
while(t->next!=NULL)
{
printf("%d->",t->data);
t=t->next;
}
}
int main()
{
struct node *p=NULL;
int a,ch=5;
while(ch--)
{
printf("\n Enter data");
scanf("%d",&a);
p=insert_beg(p,a);
display(p);
}display(p);
}
The above is a code for inserting element in the begining of the single linked link list in c.
The code compiles successfuly but when i am trying to insert an element the system hangs up... Not to locate the error. Can anyone suggest the correction i need to done.
Is there any error in the expression mentioned below... Need help.
p=insert_beg(p,a);
printf("\n address = %u --- ",*h);Also atdisplay:while(t->next!=NULL)-->while(t != NULL)%pspecifier instead of%uin yourprintf(), and don't dereferenceh(which isNULLfor the first insert). In other words, print the value of the pointer (which is the address of the node if there is one), not the value of what it points to.printf("\n address = %u --- ",*h);attempts to dereference aNULLpointer. Tryprintf("\n address = %p --- ", (void *) h);