Home >Backend Development >C++ >\'Why Does Declaring an Array with a Runtime-Determined Size Cause an \'Expected Constant Expression\' Error?\'
Error: "Expected Constant Expression" for Array Size
When attempting to declare an array with a runtime-determined size, as in the following code snippet:
<code class="cpp">int size = 100; float x[size][2];</code>
you may encounter the error "expected constant expression." This error occurs because declared arrays must have their size determined at compile time.
Solution: Use a Vector or Dynamic Array Allocation
To resolve this issue, consider using a vector or dynamic array allocation. Using a vector, you can specify the size at runtime:
<code class="cpp">std::vector< std::array<float, 2> > x(size);</code>
Alternatively, you can use the new operator to dynamically allocate the array:
<code class="cpp">float (*px)[2] = new float[size][2];</code>
Other Options:
The above is the detailed content of \'Why Does Declaring an Array with a Runtime-Determined Size Cause an \'Expected Constant Expression\' Error?\'. For more information, please follow other related articles on the PHP Chinese website!