[英]Global variable definition in C
In my code below 在下面的代码中
#include<stdio.h>
int a;
a=3;
void main(){
printf("%d",a);
}
Why am I getting the warning, 我为什么收到警告,
a.c:3:1: warning: data definition has no type or storage class [enabled by default]
In another case, when I have 在另一种情况下,当我有
#include<stdio.h>
#include<stdlib.h>
int* a;
a=(int*)malloc(sizeof(int));
void main(){
*a=3;
printf("%d",a);
}
I get error: conflicting types for 'a'
, and also warning as 我收到error: conflicting types for 'a'
,并且还警告为
warning: initialization makes integer from pointer without a cast [enabled by default]
Why? 为什么?
You can only initialise global variables with constants and it has to be done during the declaration: 您只能使用常量初始化全局变量,并且必须在声明期间完成:
int a = 3; // is valid
If you need to initialise a global variable with the return of malloc
then that has to happen during runtime. 如果您需要使用malloc
的返回值来初始化全局变量,则必须在运行时进行。
int *a;
int main() {
a = malloc(sizeof(*a));
}
Also please do not cast the return type of malloc
in C. This is a common source of errors. 另外,请不要在C中malloc
的返回类型。这是常见的错误来源。 Do I cast the result of malloc? 我要转换malloc的结果吗?
The top section (outside any function) allow only definitions, declarations and initialization but this line: 顶部(任何函数之外)仅允许定义,声明和初始化,但以下行:
a=3;
is an assignment statment and the compiler considere it as a new declaration as you didn't specify any type for a
that's why you get the error ( ... no data type...
) and also as a
is already declared as int
you get the error ( ...conflicting types...
) 被分配statment和编译器considere它作为一个新的声明,你没有为指定任何类型的a
,这就是为什么你的错误( ... no data type...
),也可以作为a
已经被声明为int
你得到错误( ...conflicting types...
)
外部变量和全局变量必须在任何函数外部准确定义一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.