Code 1 :-
int size;
struct demo
{
int a;
};
int main()
{
scanf("%d",&size);
struct demo d[size];
return 0;
}
This code works fine.
Code 2 :-
int size;
struct demo
{
int a;
};
int main()
{
scanf("%d",&size);
return 0;
}
struct demo d[size];
This code shows error :-
error : variably modified 'd' at file scope
Why such error is coming in Code 2
whereas Code 1
runs fine?
Variables declared inside functions are stack variables, which are allocated when the function is called. On the other hand, global variables are heap variables which are allocated before any function execution. That's why in the second code, it is impossible to allocate memory for array d.
Because the
d
array in the second example is global, it can't be a variable-length array; those don't get their actual size untilt runtime which isn't possible for a global. The compiler must be able to allocate room in the executable for the global data, which becomes impossible if the size isn't known.In code 2, your array of structs resides in data segment which is by definition