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


How is it possible to declare a variable-length array as a global variable ?

when variable length array is declared in a function before the length is scanned, it compiles but does not run. it gives segmentation fault. when the same declaration statement is shifted below the scanning statement, it runs fine.

in case we want a variable length array globally available to all functions, how can we do that? problem here is the that the length of the array can only be scanned through some function only.

Best Solution

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?