C语言 为什么会出现此错误:“数据定义没有类型或存储类”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18906190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why am I getting this error: "data definition has no type or storage class"?
提问by Daivid
#include <stdio.h>
#include <stdlib.h>
struct NODE {
char* name;
int val;
struct NODE* next;
};
typedef struct NODE Node;
Node *head, *tail;
head = (Node*) malloc( sizeof( Node ) ); //line 21
And I compiling like this:
我是这样编译的:
cc -g -c -o file.tab.o file.tab.c
I'm getting this error message:
我收到此错误消息:
file.y:21:1 warning: data definition has no type or storage class [enabled by default]
回答by Natan Streppel
It looks like the line
看起来像这条线
head = (Node*) malloc( sizeof( Node ) ); //line 21
is outside the main()function. You can't do that, because you can't execute code outside functions. The only thing you can do at global scope is declaring variables.Just move it inside the main()or any other function, and the problem should go away.
在main()函数之外。你不能这样做,因为你不能在函数之外执行代码。在全局范围内你唯一能做的就是声明变量。只需将其移动到main()或任何其他功能中,问题就会消失。
(PS: Take a look at this questionon why you shouldn't type-cast malloc)
(PS:看看这个问题为什么你不应该 type-cast malloc)
回答by Daivid
You need to put your code inside a function:
你需要把你的代码放在一个函数中:
#include <stdio.h>
#include <stdlib.h>
struct NODE {
char* name;
int val;
struct NODE* next;
};
typedef struct NODE Node;
main(){
Node *head, *tail;
head = (Node*) malloc( sizeof( Node ) ); //line 21
}
should work
应该管用
回答by Matt Patenaude
The problem is that you're trying to call mallocwhen you aren't executing inside of a function. If you wrap that inside a mainfunction, for example:
问题是malloc当您不在函数内部执行时,您正在尝试调用。如果将其包装在main函数中,例如:
int main(int argc, char **argv)
{
Node *head, *tail;
head = (Node*) malloc( sizeof( Node ) );
/* ... do other things ... */
return 0;
}
… it works just fine. GCC's error is a little cryptic, but the problem is basically that you're trying to initialize a variable with something that isn't a constant, which is impossible outside of a function.
......它工作得很好。GCC 的错误有点神秘,但问题基本上是你试图用不是常量的东西初始化一个变量,这在函数之外是不可能的。
回答by smnh3
Try putting the malloc and variable declarations in a main function, and delete the cast on malloc. It should look like this:
尝试将 malloc 和变量声明放在主函数中,并删除 malloc 上的强制转换。它应该是这样的:
#include <stdio.h>
#include <stdlib.h>
int main(){
struct NODE
{
char* name;
int val;
struct NODE* next;
};
typedef struct NODE Node;
Node *head, *tail;
head = malloc( sizeof(Node) ); //line 21
}

