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

前端 未结 7 720
北海茫月
北海茫月 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:37

    You don't need to tell the compiler what size the array is if you're giving an initializer. The compiler will figure out the size based on how many elements you're initializing it with.

    int a[] = {1,2,3,4,5};
    

    Then you can even let the compiler tell you the size by getting the total size of the array in bytes sizeof(a) and dividing it by the size of one element sizeof(a[0]):

    int size = sizeof(a) / sizeof(a[0]);
    

提交回复
热议问题