2017-10-08 28 views
0

我已經編寫了一段時間,但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的靜態數組呢?

+3

一些編譯器添加[可變長度數組](https://en.wikipedia.org/wiki/Variable-length_array)作爲語言的擴展。不要使用它(或指針和動態分配),而是使用['std :: vector'](http://en.cppreference.com/w/cpp/container/vector)。 –

+0

該語言被稱爲C++。 'cpp'是C預處理器。 – melpomene

+0

你如何編譯你的代碼? – melpomene

回答

1

ideone.com使用g ++編譯C++(這是在他們的FAQ中提到的)。

gcc documentation says

可變長度自動數組被允許在ISO C99,和作爲擴展GCC接受他們在C90模式和C++

(重點煤礦。)

換句話說,這是與gcc支持非標準語言的擴展。

+0

如果我正確理解[this](https://clang.llvm.org/compatibility.html#vla),clang也支持它們,*「爲了與GNU C和C99兼容程式」*。當然,他們也指出*「這個擴展在標準C++中是不允許的」*。 –

相關問題