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?
In code 2, your array of structs resides in data segment which is by definition
A data segment is a portion of virtual address space of a program,
which contains the global variables and static variables that are
initialized by the programmer. The size of this segment is determined
by the values placed there by the programmer before the program was
compiled or assembled, and does not change at run-time.
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.
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.