Array[n] vs Array[10] - 用变量 vs 实数初始化数组

2021-12-01 00:00:00 arrays initialization size c++

我的代码存在以下问题:

I am having the following issue with my code:

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] 有效.

有人知道为什么吗?

推荐答案

在 C++ 中,变长数组是不合法的.G++ 允许将其作为扩展"(因为 C 允许),因此在 G++ 中(无需 -pedantic 关于遵循 C++ 标准),您可以这样做:

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

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

如果您想要一个可变长度数组"(在 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!

或者,更好的是,使用标准容器:

Or, better yet, use a standard container:

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

如果你仍然想要一个合适的数组,你可以在创建它时使用常量,而不是变量:

If you still want a proper array, you can use a constant, not a variable, when creating it:

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

同样,如果你想从 C++11 中的函数中获取大小,你可以使用 constexpr:

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

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

相关文章