Stack中的动态数组?

Jan*_*aka 16 c++

它是否正确 ?这是用g ++(3.4)成功编译的.

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

GMa*_*ckG 17

以下是您对所有这些其他方面的组合答案:

您的代码现在不是标准C++.它标准C99.这是因为C99允许您以这种方式动态声明数组.澄清一下,这也是标准C99:

#include <stdio.h>

int main()
{
    int x = 0;

    scanf("%d", &x);

    char pz[x]; 
}
Run Code Online (Sandbox Code Playgroud)

不是标准的东西:

#include <iostream>

int main()
{
    int x = 0;
    std::cin >> x;
    char pz[x]; 
}
Run Code Online (Sandbox Code Playgroud)

它不能是标准的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
}
Run Code Online (Sandbox Code Playgroud)

如果需要动态数组,可以执行以下操作:

#include <iostream>

int main()
{
    int x = 0;
    std::cin >> x;

    char *pz = new char[x];

    delete [] pz;
}
Run Code Online (Sandbox Code Playgroud)

但你应该这样做:

#include <iostream>
#include <vector>

int main()
{
    int x = 0;
    std::cin >> x;

    std::vector<char> pz(x);
}
Run Code Online (Sandbox Code Playgroud)


CB *_*ley 13

从技术上讲,这不是C++的一部分.您可以在C99(ISO/IEC 9899:1999)中执行可变长度数组,但它们不是C++的一部分.正如您所发现的,一些编译器支持它们作为扩展.


Rob*_*edy 13

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’


Jim*_*uck 7

如果要在堆栈上使用动态数组:

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

    // blah blah blah..
}
Run Code Online (Sandbox Code Playgroud)

  • 它有效,但我想在"man alloca"中添加以下引用:"alloca()函数依赖于机器和编译器;不鼓励使用它." (8认同)

Kir*_*sky 5

在栈上分配可变长度的数组是一个好主意,因为它速度快并且不会使内存碎片。但是遗憾的是C ++ Standard不支持它。您可以通过使用模板包装器来执行此操作alloca。但是使用alloca并不是真正符合标准的。

如果要避免内存碎片和加速内存分配,标准方法是将std :: vector与自定义分配器一起使用。看一下boost :: pool_alloc以获得快速分配器的良好示例。