开发者

How to allocate memory?

I am trying to create a linked list in my program and I am not able开发者_开发知识库 to allocate memory to the structure pointer using malloc(). How do I allocate memory to variables in GCC? The sample 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);

}

The error I'm encountering is:

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


malloc is in <stdlib.h>. Include that.

Reading the man page for that function would have given you that information. It's not compiler-dependent.


malloc is declared in <stdlib.h>, so that's what you want to #include.


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

#include <stdlib.h>

instead of alloc.h.


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

To get your list printed, you have to modify p in insert. Currently, you're passing NULL every time you call insert. Change your code that way (pass a pointer-to-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 it will print

7
9
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜