C编译器错误 - 初始化不恒定 [英] C compiler error - initializer not constant

查看:137
本文介绍了C编译器错误 - 初始化不恒定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用来创建一个功能一个新的的GQueue

I have a function used to create a new GQueue

GQueue* newGQueue(int n_ele, int ele_size)
{
    GQueue* q = (GQueue*) malloc(sizeof(GQueue));
    if(!q) return NULL;

    q->ptr = malloc(n_ele * ele_size);
    if(!(q->ptr))
    {
        free(q);
        return NULL;
    }

    q->in = q->out = q->count = 0;
    q->size = n_ele; q->ele_size = ele_size;

    return q;
}

我用这样的:

挥发性的GQueue * kbdQueue = newGQueue(10,1);

然而,在这条线会出现以下编译错误:

However, the following compilation error occurs at this line:

错误:初始元素不是常数

为什么会出现这种情况? 10和1显然不应该打扰的malloc 常量等在pre C99 C $ C $角

Why does this happen? 10 and 1 are obviously constants which shouldn't bother malloc, etc in pre c99 C code.

只有标志 -Wall

感谢

推荐答案

您只能在其声明中具有恒定值, newGQueue 不是初始化的全局变量。

You can only initialize global variables at their declaration with a constant value, which newGQueue is not.

这是因为所有的全局变量必须在程序之前被初始化可以开始执行。编译器会分配给在声明全局的常量值,并使用它直接加载到程序的数据段该值当程序运行由 OS加载内存的。

This is because all global variables must be initialized before a program can begin execution. The compiler takes any constant values assigned to globals at their declaration and uses that value in the program's data segment which is loaded directly into memory by the OS loader when the program is run.

就在声明初始化kbdQueue为NULL并将其初始化主或其他启动功能的值。

Just initialize your kbdQueue at declaration to NULL and initialize it to a value in main or other startup function.

volatile GQueue * kbdQueue = NULL;

int main() {
    kbdQueue = newGQueue(10,1);
}

这篇关于C编译器错误 - 初始化不恒定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆