简体   繁体   中英

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 *));

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.

看来您只是忘记了包含<stdlib.h>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM