2013-03-18 43 views
0

要做C++我使用的是dev C++。現在我需要與Visual Studio工作C++數組Visual Studio

我做同樣的程序,但在Visual Studio中我有我以前沒有在C++中

與此

int project = (rand() % 5) + 1 ; 
int P[project][3]; 

我有一個錯誤以下錯誤:

error C2057: expected constant expression

error C2466: cannot allocate an array of constant size 0

error C2133: 'P' : unknown size

你能幫助理解這個錯誤嗎?

謝謝

回答

1

在這種情況下,您需要動態分配內存。所以你不能說int P[someVariable]。您需要使用int *mem = new int[someVariable]

看一看this link.

1

在C++中,您只能創建一個編譯時間常量大小的數組。
在編譯時需要知道數組P的大小,它應該是一個常量,編譯器會通過診斷消息向您發出警告。

Why different results on different compilers?

大多數編譯器允許您通過編譯器擴展創建變長數組,但它是非標準批准,這種用法將在不同的編譯器實現你的程序不便於攜帶。這是你的經驗。

+0

好吧,一些編譯器支持這個,但它肯定是一個擴展(請參閱http://stackoverflow.com/questions/1204521/dynamic-array-in-stack) – 2013-03-18 07:17:10

0

變長數組標準的C++類是std::vector。在這種情況下,你會得到std::vector<int> P[3]; P[0].resize(project); P[1].resize(project); P[2].resize(project);