You can't use a direct array in that case. Variable Length Arrays can only be declared in local scope. I.e. if the array size is a run-time value, then you cannot declare such array in file scope. All arrays with static storage duration shall have compile-time sizes. There's no way around it.
If your array has to declared in file scope (BTW, why?), you have to use a pointer instead and allocate memory manually using malloc
, as in
int NumOfToys;
struct toy **Square_Toys;
int main()
{
...
/* When the value of `NumOfToys` is already known */
Square_Toys = malloc(NumOfToys * sizeof *Square_Toys);
...
/* When you no longer need it */
free(Square_Toys);
...
}
Another alternative would be to stop trying to use a file scope variable and switch to a local array instead. If the array size is not prohibitively large, you will be able to use Variable Length Array in local scope.
A third alternative would be an ugly hybrid approach: declare a global pointer, but use a local VLA to allocate the memory
int NumOfToys;
struct toy **Square_Toys;
int main()
{
...
/* When the value of `NumOfToys` is already known */
struct toy *Local_Square_Toys[NumOfToys];
Square_Toys = Local_Square_Toys;
...
}
But this is here just for illustrative purposes. It is ugly.