我已經編寫了一段時間,但C++對我來說是非常新的。我知道C++中有靜態和動態數組。靜態數組在編譯期間分配內存,在堆中在運行期間動態分配。 和動態數組被聲明爲:爲什麼初始定義長度的靜態數組不會導致C++中的編譯錯誤?
data-type * variable = new data-type[value];
對於如: -
int*a = new int[n];
而且靜態數組聲明:
int a[n]; //where n already has value during the compilation time.
所以,我的問題是 -
#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
int a[n][n]; //static array
}
爲什麼這段代碼的確如此不運行編譯錯誤,因爲n的值是在運行時定義的。那麼怎樣才能在編譯過程中定義帶變量n的靜態數組呢?
一些編譯器添加[可變長度數組](https://en.wikipedia.org/wiki/Variable-length_array)作爲語言的擴展。不要使用它(或指針和動態分配),而是使用['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)。 –
該語言被稱爲C++。 'cpp'是C預處理器。 – melpomene
你如何編譯你的代碼? – melpomene