i wanted to know why memory allocation is necessary for the pointer variable i am declaring.
my doubt is when i am declaring a new pointer of list type i am creating doesn't it get the required memory allocated automatically?why i have to specifically assign it?
here is the code due to which i came up with such a question(i am not sure if i asked the correct thing)
anyway here it is:
#include<stdio.h>
#include<malloc.h>
typedef struct list
{
int info;
struct list *link;
}node;
void insertatbeg(node **start)
{
node *ptr;
node *new1;
int d;
ptr=(node*)malloc(sizeof(node));
printf("enter the element you want to insert");
scanf("%d",&d);
ptr->info=d;
ptr->link=*start;
*start=ptr;
// printf("value of *start in beg func = %u",*start);
}
void insertatend(node **start)
{
node *ptr,*gptr;
int d;
gptr=(node *)malloc(sizeof(node));
//printf("\n *start=%d",*start);
ptr=*start;
while (ptr->link!=NULL)
{
ptr=ptr->link;
}
printf("enter the element");
//scanf("%d",&gptr->info);
scanf("%d",&d);
gptr->info=d;
gptr->link=ptr->link;
ptr->link=gptr;
}
void createlist(node **start)
{
int n,j=0;
printf("enter the number of elements you want to insert");
scanf("%d",&n);
while (j<n)
{
if (*start==NULL)
{
insertatbeg(start);
}
else
{
insertatend(start);
}
j++;
}
}
void display(node **start)
{
node *ptr=*start;
while (ptr!=NULL)
{
printf("\t%d",ptr->info);
ptr=ptr->link;
}
}
main()
{
node *start1=NULL;
createlist(&start1);
display(&start1);
system("pause");
}
My doubts:
1. In the insertatbeg() if i'll make the following line comment the proogram will still work perfectly:
ptr=(node*)malloc(sizeof(node));
2.But in the insertatend() if i'll make the following line comment the program crashes:
gptr=(node *)malloc(sizeof(node));


Sign In
Create Account

Back to top









