Why can’t the size of a static array be made variable?

Since the size of the array you declare is not constant, what you have is an Variable Length Array(VLA). VLA are allowed by the c99 standard but there are some limitations associated with it. You cannot have an variable length array with static or extern storage class specifier.

You have an VLA with static storage specification and it is not allowed by the C99 Standard.

Reference:

c99 Standard: 6.7.5.2/8

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 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.

So if you want a dynamic size array with static storage specifier you will have to use a dynamic array allocated on heap.

#define MAX_SIZE 256
static int* gArr;
gArr = malloc(MAX_SIZE * sizeof(int));

EDIT:
To answer your updated question:
When you remove the static keyword from the declaration, the storage specifier of the declared array changes from static to global, note the standard quote above, it clearly mentions the restriction that VLAs are not allowed with static and extern storage specification. Clearly, you are allowed to have an VLA with global storage specification, which is what you have once you remove the static keyword.

Leave a Comment