Home >Backend Development >C++ >How to Fix the \'Expected Constant Expression\' Error When Declaring Arrays in C ?
Resolving "Expected Constant Expression" Error for Array Size
Consider the following C code:
<code class="cpp">int count = 0; float sum = 0; float maximum = -1000000; std::ifstream points; int size = 100; float x[size][2]; // <<< Error
This code raises an "expected constant expression" error when declaring the array x. This error occurs because C requires non-static array sizes to be known at compile time.
Solution Using Vectors
To resolve this issue, we can use a C vector instead of an array:
<code class="cpp">std::vector<std::array<float, 2>> x(size);</code>
Solution Using new
Another approach involves dynamically allocating the array using the new operator:
<code class="cpp">float (*px)[2] = new float[size][2];</code>
Alternative Solutions
Considerations for Non-C 11 Compilers
If you don't have C 11 support, use the following techniques:
The above is the detailed content of How to Fix the \'Expected Constant Expression\' Error When Declaring Arrays in C ?. For more information, please follow other related articles on the PHP Chinese website!