Home > Backend Development > C++ > body text

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

Linda Hamilton
Release: 2024-10-25 13:04:03
Original
543 people have browsed it

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
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!