Why can't I create an array with size determined by a global variable?

前端 未结 7 719
北海茫月
北海茫月 2020-11-27 06:11

Why does the array a not get initialized by global variable size?

#include

int size = 5;

int main()
{
    int a[si         


        
7条回答
  •  星月不相逢
    2020-11-27 06:18

    The compiler needs to know the size of the array while declaring it. Because the size of an array doesn't change after its declaration. If you put the size of the array in a variable, you can imagine that the value of that variable will change when the program is executed. In this case, the compiler will be forced to allocate extra memory to this array. In this case, this is not possible because the array is a static data structure allocated on the stack. I hope that this will help.

提交回复
热议问题