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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15013077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:53:30  来源:igfitidea点击:

Array[n] vs Array[10] - Initializing array with variable vs real number

c++arraysinitializationsize

提问by msmf14

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};

Returns the following error:

返回以下错误:

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

Whereas using double tenorData[10]works.

而使用double tenorData[10]作品。

Anyone know why?

有谁知道为什么?

回答by Cornstalks

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

在 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:

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

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:

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

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

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

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

constexpr int n()
{
    return 10;
}

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