declaring a variable-length array as a global variable in C

A variable length array (i.e. an array sized with a runtime value) can't be a global variable, because the expression you are using for the size must obviously be computed at compile time. It can only live on the stack. Presumably what you are getting is a static array with a size that depends on where in the code you are defining it (because you are redefining something it depends on).

Why can't you just use a global pointer and realloc() to size it as needed?


You can't do that. Here's what the draft of the standard says:

6.7.6.2 Array declarators

2 If an identifier is declared as having a variably modified type, it shall be an ordinary identifier (as defined in 6.2.3), have no linkage, and have either block scope or function prototype scope. If an identifier is declared to be an object with static or thread storage duration, it shall not have a variable length array type.

Also,

10 EXAMPLE 4 All declarations of variably modified (VM) types have to be at either block scope or function prototype scope. Array objects declared with the _Thread_local, static, or extern storage-class specifier cannot have a variable length array (VLA) type. However, an object declared with the static storage-class specifier can have a VM type (that is, a pointer to a VLA type). Finally, all identifiers declared with a VM type have to be ordinary identifiers and cannot, therefore, be members of structures or unions.


There's no way to declare a variable length array as a global variable in C as it would have to be allocated before the knowing its size so the compiler can't know how much memory it should allocate for it. What you can (and should) do, however, is to allocate it dynamically:

char* my_dynamic_array = NULL;

void f(unsigned int size)
{
    if(!my_dynamic_array) {
        my_dynamic_array = malloc(size);
    }
    /* do something with the array */
}

int main(void)
{
    f(1024); /* set size dynamically */
    /* do something with the array */
    free(my_dynamic_array); /* free the allocated memory */
    return 0;
}