數組大小混亂導致錯誤
聲明動態大小的float 數組時,如:
<code class="cpp">int size = 100; float x[size][2];</code>
您可能🎜 >您可能會遇到「預期常數表達式」錯誤。出現這種情況是因為 C 要求陣列在編譯時具有固定大小,而不是在執行時確定。這裡的 size 變數不能用作有效的數組維度。
使用向量的解
要避免此問題,請考慮使用向量:
<code class="cpp">std::vector<std::array<float, 2>> x(size);</code>
這將建立一個陣列向量,每個陣列包含兩個浮點數。
替代解決方案
或者,您可以使用new 的原始記憶體分配或建立自己的記憶體分配數組類型:
<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>
其他選項
其他選項包括使用成對向量或使用語法助理捲動您自己的陣列類型:
<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>
以上是為什麼在 C 中宣告具有動態大小的浮點數組會導致「預期常數表達式」錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!