关于malloc结构数组的困惑

时间:2013-12-12 16:08:54

标签: c arrays pointers struct malloc

好的,我有以下结构

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

我试图使用以下

动态分配它
fscanf(iStream, "%d %d", &nTasks, &nRules);

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

但是Eclipse显示了

  

.. \ GraphSort.c:62:18:警告:隐式声明函数   'malloc'[-Wimplicit-function-declaration] graph =(struct node *)   malloc(nTasks * sizeof(struct node));                     ^

  

.. \ GraphSort.c:62:26:警告:不兼容的隐式声明   内置函数'malloc'[默认启用] graph =(struct node   *)malloc(nTasks * sizeof(struct node));                             ^

我不明白为什么。不是表示为指向第一个元素的指针的数组吗?

还有一点,我有这个声明没有显示警告

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

2 个答案:

答案 0 :(得分:5)

implicit declaration of function 'malloc'表示您没有包含正确的头文件,告诉您的程序如何调用malloc。尝试添加到程序的开头:

#include <stdlib.h>

你的其他代码不是“声明”,它只是一系列声明。编译器只会警告您一次未能为它编译的每个文件声明malloc()

答案 1 :(得分:2)

您似乎忘了加入<stdlib.h>