How to allocate memory?

I am trying to create a linked list in my program and I cannot allocate memory to the structure pointer using malloc (). How to allocate memory for variables in GCC? An example program is given below. How to make it work in gcc?

#include<stdio.h> #include <alloc.h> struct node { int data; struct node * link; }; void insert (struct node *p, int d) { struct node *temp; temp = malloc(sizeof(struct node)); temp->data=d; temp->link=NULL; if(p==NULL) { p=temp; } else{ while(p->link!=NULL) p=p->link; p->link=temp; } } void disp(struct node *p) { while(p!=NULL) { printf("%d\n",p->data); p=p->link; } } int main() { struct node *p; p=NULL; insert(p,7); insert(p,9); disp(p); } 

I encountered an error:

 Line 18: error: alloc.h: No such file or directory In function 'insert': Line 13: warning: incompatible implicit declaration of built-in function 'malloc' 
0
source share
4 answers

malloc is located in <stdlib.h> . Turn it on.

Reading the man page for this feature would provide you with this information. It does not depend on the compiler.

+7
source

malloc declared in <stdlib.h> , so you want #include .

+2
source

The definition of malloc is in the stdlib.h file:

 #include <stdlib.h> 

instead of alloc.h .

+1
source

As others say: your error occurs because you have to include stdlib.h instead of alloc.h

To print your list, you must change p to insert . You are currently passing NULL every time you call insert . Change your code this way (pass a pointer to a pointer to insert ):

 #include <stdio.h> #include <stdlib.h> struct node { int data; struct node * link; }; /* note **p instead of *p */ void insert (struct node **p, int d) { struct node *temp; temp = malloc(sizeof(struct node)); temp->data=d; temp->link=NULL; if(*p==NULL) { *p=temp; } else{ while((*p)->link!=NULL) *p=(*p)->link; (*p)->link=temp; } } void disp(struct node *p) { while(p!=NULL) { printf("%d\n",p->data); p=p->link; } } int main() { struct node *p; p=NULL; insert(&p,7); insert(&p,9); disp(p); } 

and he will print

 7 9 
+1
source

All Articles