Andreas Andreou
Andreas Andreou

Reputation: 848

Confusion about malloc an array of struct

Ok, so I have the following struct

struct node {
    int visited;
    struct node **depend;
};

and I am trying to allocate it dynamically using the following

fscanf(iStream, "%d %d", &nTasks, &nRules);

    graph = (struct node *) malloc(nTasks * sizeof(struct node));

but Eclipse shows an

..\GraphSort.c:62:18: warning: implicit declaration of function 'malloc' [-Wimplicit-function-declaration] graph = (struct node *) malloc(nTasks * sizeof(struct node)); ^

and

..\GraphSort.c:62:26: warning: incompatible implicit declaration of built-in function 'malloc' [enabled by default] graph = (struct node *) malloc(nTasks * sizeof(struct node)); ^

What I don't understand is why. Isn't an array represented as a pointer to the first element?

Also a little further I have this declaration which shows no warnings

fscanf(iStream, "%d, %d", &taskId, &dependencies);
        graph[taskId-1].visited = 0;
        graph[taskId-1].depend = (struct node **) malloc(dependencies * sizeof(struct node *));

Upvotes: 1

Views: 476

Answers (2)

jmlemetayer
jmlemetayer

Reputation: 4952

It seems that you just forgot to include <stdlib.h>.

Upvotes: 2

Tim Pierce
Tim Pierce

Reputation: 5664

implicit declaration of function 'malloc' is an indicator that you haven't included the proper header file that tells your program how to call malloc. Try adding to the beginning of your program:

#include <stdlib.h>

Your other bit of code is not a "declaration," it's just a series of statements. The compiler will only warn you once about failing to declare malloc() for each file that it compiles.

Upvotes: 5

Related Questions