Home  >  Article  >  Backend Development  >  \"Why Does Declaring an Array with a Runtime-Determined Size Cause an \"Expected Constant Expression\" Error?\"

\"Why Does Declaring an Array with a Runtime-Determined Size Cause an \"Expected Constant Expression\" Error?\"

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 04:10:29387browse

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:

  • Boost Array: If you do not have C 11, use Boost library's boost::array.
  • Custom Array Type: Create a custom array type that can be placed in a vector.
  • Identity Template: Simplify syntax for dynamic array allocation using an identity template.
  • Vector of Pairs: Use a vector of std::pair to store the data.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn