C++ forbids variable-size array

后端 未结 3 1888
面向向阳花
面向向阳花 2021-01-17 08:18

I am using some existing code that someone else has written, and I cannot get it to compile (limited C experience here but I am trying to learn!).

utilities.

相关标签:
3条回答
  • 2021-01-17 09:06

    The error is correct. VLA(variable size arrays) are forbidden in C++. This is a VLA:

    char filename1char[filenameLength];
    

    What you probably meant is this:

    char *filename1 = new char[filenameLength];
    

    Which is not a VLA, but an array of chars allocated on the heap. Note that you should delete this pointer using operator delete[]:

    delete[] filename1;
    
    0 讨论(0)
  • 2021-01-17 09:09

    They are forbidden, but a workaround is to use a stack allocator, for example:

    http://howardhinnant.github.io/stack_alloc.html

    You can use the stack allocator with a ::std::vector (or with some other container, or just directly) and you've got yourself a VLA.

    0 讨论(0)
  • 2021-01-17 09:15

    Try this instead

        char *filename1 = new char[filenameLength];
    

    you cannot create an array as a local variable length array on the stack like this

        char filename1[filenamelength];
    

    unless filenamelength is declared as const.

    Also as you have allocated memory for an array, you should free the memory using

       delete [] filename1;
    

    otherwise you will have a memory leak. Also it is not essential to have parentheses around your return values;

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