簡體   English   中英

Stack中的動態數組?

[英]Dynamic array in Stack?

它是否正確 ? 這是用g ++(3.4)成功編譯的。

int main()
{
    int x = 12;
    char pz[x]; 
}

以下是您對所有這些其他方面的組合答案:

您的代碼現在不是標准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 ++的一部分。 您可以在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..
}

在堆棧上分配具有可變長度的數組是一個好主意,因為它快速且不會碎片化內存。 但不幸的是,C ++標准不支持它。 您可以通過使用模板的包裝要做到這一點alloca功能。 但是使用alloca並不是真正符合標准的。

標准方法是使用std :: vector和自定義分配器,如果你想避免內存碎片和加速內存分配。 看一下boost :: pool_alloc ,獲得快速分配器的一個很好的樣本。

實際上,如果你想創建一個動態數組,你應該使用std :: vector,如:

#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標准中受支持。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM