Home > Backend Development > C++ > Why Does Declaring a Float Array with a Dynamic Size Result in an \'Expected Constant Expression\' Error in C ?

Why Does Declaring a Float Array with a Dynamic Size Result in an \'Expected Constant Expression\' Error in C ?

DDD
Release: 2024-10-26 13:46:03
Original
900 people have browsed it

Why Does Declaring a Float Array with a Dynamic Size Result in an

Array Size Confusion Causes Error

When declaring a float array with a dynamic size, such as:

<code class="cpp">int size = 100;
float x[size][2];</code>
Copy after login

you may encounter an "expected constant expression" error. This occurs because C requires arrays to have fixed sizes at compile time, not determined during runtime. The size variable here cannot be used as a valid array dimension.

Solution with Vector

To avoid this issue, consider using a vector:

<code class="cpp">std::vector<std::array<float, 2>> x(size);</code>
Copy after login

This creates a vector of arrays, each array containing two floats.

Alternative Solutions

Alternatively, you could use raw memory allocation with new or create your own array type:

<code class="cpp">// With new
float (*px)[2] = new float[size][2];

// With custom array type
template<typename T, size_t N>
struct array {
  T data[N];
};

array<float, 2> myArray[size];</code>
Copy after login

Additional Options

Other options include using a vector of pairs or rolling your own array type with syntax helpers:

<code class="cpp">// Vector of pairs
std::vector<std::pair<float, float>> x(size);

// Custom array type
template<typename T>
struct identity {
  typedef T type;
};

using FloatArray2 = identity<float[2]>::type;
FloatArray2 myArray[size];</code>
Copy after login

The above is the detailed content of Why Does Declaring a Float Array with a Dynamic Size Result in an \'Expected Constant Expression\' Error 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template