c arrays: setting size dynamically?

后端 未结 4 768
余生分开走
余生分开走 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.

    0 讨论(0)
  • 2021-01-18 11:54

    To create an array of a non-constant size (i.e. known at compile time), you need to dynamically allocate space for it using malloc() (and correspondingly deallocate it using free() when it is no longer required).

    As others have noted, the ability to declare dynamic arrays is available in C99 compliant compilers.

    0 讨论(0)
  • 2021-01-18 12:00

    use either of these

    GLubyte* vertsArray = (GLubyte*) malloc(sizeof(GLubyte) * bound);
    
    GLubyte* vertsArray = new GLubyte[bound];
    

    remember to free the memory when you don't need the object anymore

    delete [] vertsArray;
    
    free((void*)vertsArray;
    

    Despite what they say in the comments I still say that you should prefer new instead of malloc if you are not 100% forced to use C. See this link for more information

    0 讨论(0)
  • 2021-01-18 12:04

    What you want is possible in C99; however, with earlier versions of C, you are stuck calling functions to dynamically allocate memory, e.g. alloca(3) or malloc(3).

    0 讨论(0)
提交回复
热议问题