简体   繁体   中英

C compiler error - initializer not constant

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;
}

I use it like this:

volatile GQueue * kbdQueue = newGQueue(10, 1);

However, the following compilation error occurs at this line:

Error: initializer element not constant

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

Only flag is -Wall .

Thanks

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

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.

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);
}

The problem is not in the arguments for newGQueue, is for using the newGQueue return value to initialize kbdQueue. That's executable code, and in C all initializers have to be known at compile time. This is a problem in C only; C++ would accept it without problems.

If you break apart the declaration and initialization it should work OK.

volatile GQueue * kbdQueue;
kbdQueue = newGQueue(10, 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM