Why can't the size of a static array be made variable?

后端 未结 4 1166
猫巷女王i
猫巷女王i 2020-11-28 12:20

Related but not quite duplicate as it discusses C++:
can we give size of static array a variable

I am definin

4条回答
  •  无人及你
    2020-11-28 12:45

    You are allocating the array at compile-time, so the compiler has to know the array's size in advance. You have to declare siz as a constant expression before you declare arr, for instance:

    #define siz 5
    

    or

    enum ESizes
    {
        siz = 5
    };
    

    Alternatively, if you need to determine its size in run-time, you can allocate it on the heap by using malloc:

    static int* arr;
    arr = (int*)malloc(siz * sizeof(int))
    

    EDIT: as eddieantonio has mentioned, my answer is valid for C89. In C99 it is allowed to declare arrays of variable size.

提交回复
热议问题