-6

I have a code segment which goes something like this

typedef struct node* node_t;

struct node{
int value;
node_t link;
};

......
......
......

//now I want to allocate memory somewhere else in the program.
node_t x;
x=(node_t) malloc(sizeof *x);

Could you please tell me if the above statement is proper? Eclipse shows this warning

warning: implicit declaration of function ‘malloc’ [-Wimplicit-function-declaration]
../tree.c:22:9:
warning: incompatible implicit declaration of built-in function ‘malloc’    

Can someone explain in detail about situations like this? What is actually wrong with this. I would really appreciate if you could list all the possible ways in which I can allocate memory in this program? Thank you in advance..

4

4 回答 4

1

为了使用malloc,您需要包含<stdlib.h>. 此外,分配内存,如

node_t x = malloc(sizeof node_t);

您不能将内存分配给堆栈变量,而只能分配给指针。并且永远不要转换回分配的类型,作为malloc返回void*,这不需要显式转换。

于 2013-03-23T07:57:37.840 回答
0

You need an

#include <stdlib.h>

before you use malloc. You apparently declared the function wrong in your source. Never declare C standard library functions. Just include the headers that declare them.

于 2013-03-23T07:54:20.743 回答
0

Could you please tell me if the above statement is proper?

No, it isn't: you're casting the return value of malloc() and you're missing the <stdlib.h> header.

于 2013-03-23T07:55:09.590 回答
0

您收到警告是因为您没有malloc范围内的声明;您需要包含stdlib.h头文件:

#include <stdlib.h>

你也应该放弃演员表。这不是必需的,并且在其他编译器下会抑制您尝试将int值分配给指针类型的诊断。

不要将指针隐藏在 typedef 后面。这几乎总是一个坏主意。

于 2013-03-23T11:23:35.170 回答