C++ forbids variable-size array

C++ forbids variable-size array

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;

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;

C++ forbids variable-size array

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 youve got yourself a VLA.

Leave a Reply

Your email address will not be published.