error : variably modified 'd' at file scop

2019-05-14 03:26发布

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?

3条回答
Explosion°爆炸
2楼-- · 2019-05-14 04:02

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.

查看更多
Fickle 薄情
3楼-- · 2019-05-14 04:15

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.

查看更多
我命由我不由天
4楼-- · 2019-05-14 04:20

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.

查看更多
登录 后发表回答