c arrays: setting size dynamically?

后端 未结 4 804
余生分开走
余生分开走 2021-01-18 11:25

I am new to C programming. I am trying to set the size of the array using a variable but I am getting an error: Storage size of \'array\' isn\'t constant !!

4条回答
  •  灰色年华
    2021-01-18 11:54

    You are getting this error because, as the compiler told you, your array size is not constant. In C89/90 version of C language array size has to be a constant. You can't "set the size of the array dynamically". If you need a run-time sized array, you have to either allocate it manually with malloc or use some non-standard compiler-specific approach (like alloca function).

    In C99 version of C language support for so called Variable-Length Arrays (VLA) was added. A C99 compiler would accept run-time sized array declaration for an automatic array. Yet even in C99 you can't declare a static array of run-time size, as you are trying to.

提交回复
热议问题