繁体   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