Home  >  Article  >  Backend Development  >  How to Fix the \"Expected Constant Expression\" Error When Declaring Arrays in C ?

How to Fix the \"Expected Constant Expression\" Error When Declaring Arrays in C ?

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 13:04:03544browse

How to Fix the

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

  • Use Boost: If you have access to the Boost library, you can use boost::array instead of std::array.
  • Define Custom Array Type: Define a custom array type that supports dynamic sizing and use it in a vector.

Considerations for Non-C 11 Compilers

If you don't have C 11 support, use the following techniques:

  • Use an identity template to simplify the syntax when using new.
  • Use a vector of std::pair as an alternative to the vector solution mentioned earlier.

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!

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