Array [ n ] vs Array [10]-使用变量 vs 数值文字初始化数组

我的代码有以下问题:

int n = 10;
double tenorData[n]   =   {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

返回以下错误:

error: variable-sized object 'tenorData' may not be initialized

而使用 double tenorData[10]就可以了。

Anyone know why?

262023 次浏览

在 C + + 中,可变长度数组是不合法的。G + + 允许它作为一个“扩展”(因为 C 允许它) ,所以在 G + + 中(不需要 -pedantic来遵循 C + + 标准) ,你可以这样做:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

或者,更好的做法是,使用一个标准容器:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

如果仍然需要合适的数组,可以在创建时使用 不变,而不是 变量:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

类似地,如果想从 C + + 11中的函数获得大小,可以使用 constexpr:

constexpr int n()
{
return 10;
}


double a[n()]; // n() is a compile time constant expression