Home  >  Article  >  Backend Development  >  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
DDDOriginal
2024-10-26 13:46:03829browse

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>

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>

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>

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>

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!

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