Error: modified "d" in the file area

Code 1: -

int size;

struct demo
{
    int a;
};

int main()
{
    scanf("%d",&size);
    struct demo d[size];
    return 0;
}

This code works great.

Code 2: -

int size;

struct demo
{
    int a;
};

int main()
{
    scanf("%d",&size);
    return 0;
}

struct demo d[size];

This code shows the error: -

error : variably modified 'd' at file scope

Why does such an error occur in Code 2, while how it Code 1works fine?

+3
source share
3 answers

In code 2, your array of structures is in the data segment, which by definition

A data segment is part of the virtual address space of a program that contains 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 runtime .

+3

d , ; , , . , , .

+2

Variables declared inside functions are stack variables that are allocated when the function is called. Global variables, on the other hand, are heap variables that are allocated before any function is executed. Therefore, in the second code, it is impossible to allocate memory for the array d.

+2
source

All Articles