2009-07-30 28 views

回答

12

從技術上講,這不是C++的一部分。你可以在C99(ISO/IEC 9899:1999)中做變長數組,但它們不是C++的一部分。正如你發現的,它們被一些編譯器支持作爲擴展。

10

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’ 
6

如果你想在堆棧上的動態數組:

void dynArray(int x) 
{ 
    int *array = (int *)alloca(sizeof(*array)*x); 

    // blah blah blah.. 
} 
+6

它的工作原理,但我想從「man alloca」添加下面的引用:「alloca()函數是依賴於機器和編譯器的,它的使用是不鼓勵的。 – 2009-07-30 05:11:06

2

實事求是地講,如果你想使一個動態數組,你應該使用的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標準中受支持。

+0

不會在堆上分配內存嗎?考慮到問題的標題,我的印象是,OP希望它在堆棧中分配。 – mrduclaw 2009-07-30 05:32:33

13

這裏的所有這些其他的你的答案組合:

您的代碼現在的問題是標準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); 
} 
3

分配在棧上變長數組是一個很好的的想法,因爲它速度快,不會碎裂內存。但不幸的是C++標準不支持它。你可以通過使用模板包裝來達到alloca的功能。但使用alloca實際上並不符合標準。

標準方法是使用std :: vector與定製分配器如果要避免內存碎片和加速內存分配。看看boost::pool_alloc是快速分配器的一個很好的例子。