回答
從技術上講,這不是C++的一部分。你可以在C99(ISO/IEC 9899:1999)中做變長數組,但它們不是C++的一部分。正如你發現的,它們被一些編譯器支持作爲擴展。
G ++支持C99功能,允許動態調整大小的數組。它不是標準的C++。 G ++有-ansi
選項關閉了一些不在C++中的功能,但這不是其中之一。爲了使G ++拒絕代碼,使用-pedantic
選項:
$ g++ -pedantic junk.cpp junk.cpp: In function ‘int main()’: junk.cpp:4: error: ISO C++ forbids variable-size array ‘pz’
如果你想在堆棧上的動態數組:
void dynArray(int x)
{
int *array = (int *)alloca(sizeof(*array)*x);
// blah blah blah..
}
實事求是地講,如果你想使一個動態數組,你應該使用的std ::載體,如:
#include <iostream> #include <cstdlib> #include <vector> int main(int argc, char* argv[]) { int size; std::cin>>size; std::vector<int> array(size); // do stuff with array ... return 0; }
如果你只是好奇的語法,那麼你正在尋找的是:
//... int* array = new int[size]; // Do stuff with array ... delete [] array; //...
這些都沒有分配本地存儲。標準C++目前不支持使用本地存儲自動分配的動態大小的數組,但在當前的C標準中受支持。
不會在堆上分配內存嗎?考慮到問題的標題,我的印象是,OP希望它在堆棧中分配。 – mrduclaw 2009-07-30 05:32:33
這裏的所有這些其他的你的答案組合:
您的代碼現在的問題是不標準C++。它是標準C99。這是因爲C99允許您以這種方式動態聲明數組。爲了澄清,這也是標準C99:
#include <stdio.h>
int main()
{
int x = 0;
scanf("%d", &x);
char pz[x];
}
這不標準任何東西:
#include <iostream>
int main()
{
int x = 0;
std::cin >> x;
char pz[x];
}
它不能是標準C++,因爲這需要恆定陣列的尺寸,並且它不能被標準C,因爲C沒有std::cin
(或命名空間,或班級等)
爲了使C++標準,這樣做:
int main()
{
const int x = 12; // x is 12 now and forever...
char pz[x]; // ...therefore it can be used here
}
如果你想有一個動態數組,你可以做到這一點:
#include <iostream>
int main()
{
int x = 0;
std::cin >> x;
char *pz = new char[x];
delete [] pz;
}
但是,你應該這樣做:
#include <iostream>
#include <vector>
int main()
{
int x = 0;
std::cin >> x;
std::vector<char> pz(x);
}
分配在棧上變長數組是一個很好的的想法,因爲它速度快,不會碎裂內存。但不幸的是C++標準不支持它。你可以通過使用模板包裝來達到alloca
的功能。但使用alloca
實際上並不符合標準。
標準方法是使用std :: vector與定製分配器如果要避免內存碎片和加速內存分配。看看boost::pool_alloc是快速分配器的一個很好的例子。
- 1. C++數組:Stack與堆
- 2. java stack從數組中讀取ArrayIndexOutOfBoundsException
- 3. malloc動態數組中的動態數組結構
- 4. 動態數組中的jQuery
- 5. c中的動態數組#
- 6. C++中的動態數組
- 7. 靜態數組的動態數組
- 8. 靜態數組和動態數組中元素的數量
- 9. 動態數組
- 10. 動態數組
- 11. MVC中的動態圖像(Stack Exchange Beta站點)
- 12. CLI中整數的動態數組
- 13. 動態數值數組中的動態閾值確定
- 14. 靜態或動態數組
- 15. 動態和靜態數組
- 16. PHP - 按動態鍵數組的數組
- 17. 一類中的類的動態數組
- 18. 與動態數組
- 19. Java動態數組
- 20. 動態數組名
- 21. OCaml:動態數組?
- 22. c99動態數組
- 23. Android動態數組
- 24. delphi動態數組
- 25. 動態數組鍵
- 26. FASM:動態數組
- 27. 從動態數組
- 28. C動態數組
- 29. 動態數組類
- 30. 動態數組C++
它的工作原理,但我想從「man alloca」添加下面的引用:「alloca()函數是依賴於機器和編譯器的,它的使用是不鼓勵的。 – 2009-07-30 05:11:06