Array [n] vs Array [10] - 初始化具有變量與實數的數組我的代碼出現以下問題:int n = 10;double tenorData[n] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};返回以下錯誤:error: variable-sized object 'tenorData' may not be initialized而使用double tenorData[10]作品。誰知道為什么?
2 回答

海綿寶寶撒
TA貢獻1809條經驗 獲得超8個贊
在C ++中,可變長度數組是不合法的。G ++允許將其作為“擴展”(因為C允許),因此在G ++中(不-pedantic
遵循C ++標準),您可以:
int n = 10;double a[n]; // Legal in g++ (with extensions), illegal in proper C++
如果你想要一個“可變長度數組”(在C ++中更好地稱為“動態大小的數組”,因為不允許使用適當的可變長度數組),你必須自己動態分配內存:
int n = 10;double* a = new double[n]; // Don't forget to delete [] a; when you're done!
或者,更好的是,使用標準容器:
int n = 10;std::vector<double> a(n); // Don't forget to #include <vector>
如果你仍然需要一個合適的數組,你可以在創建它時使用常量而不是變量:
const int n = 10;double a[n]; // now valid, since n isn't a variable (it's a compile time constant)
同樣,如果你想從C ++ 11中的函數中獲取大小,你可以使用constexpr
:
constexpr int n(){ return 10;}double a[n()]; // n() is a compile time constant expression
添加回答
舉報
0/150
提交
取消