Since the size of the declared array is not constant, you have a Variable Length Array (VLA) . VLAs are allowed by the c99 standard, but there are some limitations associated with it. You cannot have a variable length array with a static
or extern
storage class specifier.
You have a VLA with a static
storage specification, and it is not allowed by the C99 standard.
Link:
c99 Standard: 6.7.5.2/8
EXAMPLE 4 All declarations of types with variable modification (VM) should be both in the block area and in the scope of the prototype. Array objects declared with a static or external storage class specification cannot be of variable length type (VLA) . However, an object declared with a static storage class specification may have a virtual machine type (that is, a pointer to a VLA type). Finally, all identifiers declared with a VM type must be regular identifiers and therefore cannot be members of structures or associations.
So, if you need a dynamic-sized array with a static
storage specifier, you will have to use a dynamic array allocated to the 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
from the declaration, the storage specifier of the declared array changes from static
to global, pay attention to the standard quote above, it clearly indicates the limitation that the VLA is not allowed using the static
and extern
storage specification. Obviously, you are allowed to have a VLA with a global repository specification, which was after removing the static
.
source share