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

人气:803 发布:2022-10-16 标签: arrays c++ size initialization

问题描述

我的代码有以下问题:

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++中(无需遵循C++标准),您可以:

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

如果您想要"可变长度数组"(在C++中更好地称为"动态大小数组",因为不允许使用适当的可变长度数组),您要么必须自己动态分配内存:

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

818