How to create a variable size char array in VC++

arrays, c++, mfc, visual-studio

Solution

In the current version of C++, arrays must have a fixed size, specified by a compile-time constant. If you need to use a run-time value, then your options are:

- most portably, use a dynamic array class such as `std::string` or `std::vector<char>`;

- use a compiler that supports C99 variable-length arrays as a non-standard extension;

- wait a year for dynamic arrays to (hopefully) be introduced in C++14 (and perhaps wait a bit longer for your compiler vendor to catch up).

Problem

``` const int sizea = 600; char sz[sizea]; ``` above code works fine. But below code segment cause errors. I'm working on visual studio 2005 - MFC application ``` CString strFinal; .......//strFinal value is dynamically changing . . const int size = strFinal.GetLength(); char sz[size]; ``` Error 2 error C2057: expected constant expression Error 5 error C2070: 'char []': illegal sizeof operand Error 4 error C2133: 'sz' : unknown size Error 3 error C2466: cannot allocate an array of constant size 0

Original source

Related problems