C语言:initializer element is not constant

static struct QueuePtr * header =( ( struct QueuePtr * ) malloc(sizeof(struct QueuePtr ) ) );
在编译时报错:initializer element is not constant 
原因:在c99中指明全局变量和static变量的初始化式必须为常量表达式
修改:
static struct QueuePtr * header = NULL;
header = ( ( struct QueuePtr * ) malloc(sizeof(struct QueuePtr ) ) );


查阅其他博客,看到以下代码也会报同样的错误:
链接:为什么出现“initializer element is not constant”错误 
#include <stdio.h>  
int a = 1;  
int b = 2;  
int c = a+b;  
  
int main() {  
    printf("c is %d\n", c);  
    return 0;  
}  
同理,上述代码中全局变量c的值是在执行时才确定的。全局变量的初始化是在编译阶段完成的,因此不可以是尚未确定其值的变量。


(1)c语言中全局变量和static变量的初始化需要指定一个常量,不能是一个非常量的表达式;
(2)作为全局变量,在编译之后就要确定它的地址,如果这个全局变量是个结构体的话,那么结构体里面的各个成员的具体值也要确定了。因为全局变量是存储在静态区,而只有常量表达式才可以前期确定值,而不是具体运行时确定值。
(3)依据:
C99标准 6.7.8 Initialization 第4款: 
4 All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值