【发布时间】:2019-12-29 03:02:54
【问题描述】:
好的,这个问题似乎很愚蠢,但请耐心等待。当我尝试在 C++ 中创建一个二维数组时,它给了我一些警告(len 是一个整数):
double a[len][len];
// warning: variable length arrays are a C99 feature
// warning: variable length array used
所以我尝试了另一个:
double **a = new double[len][len];
// error: only the first dimension of an allocated array may have dynamic size
// read of non-const variable 'len' is not allowed in a constant expression
如何在C++11 中正确操作?
【问题讨论】:
-
std::vector<std::vector<int>> a(len, std::vector<int>(len)); -
数组尺寸必须保持不变。一些编译器将允许第一段代码更像 C。不过,这是一种将顶部从堆栈中吹走的绝妙方法。如果您事先不知道尺寸,我建议您使用something more like this。您仍然可以获得连续存储,但它位于动态存储中,通常您拥有更多内存。
-
有很多方法可以通过不同的权衡来做到这一点。