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

Array[n] vs Array[10] - Initializing array with variable vs real number(Array[n] vs Array[10] - 用变量和实数初始化数组)

本文介绍了Array[n] vs Array[10] - 用变量和实数初始化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码存在以下问题:

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++ 中(没有关于遵循 C++ 标准的-pedantic),你可以这样做:

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

这篇关于Array[n] vs Array[10] - 用变量和实数初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Array[n] vs Array[10] - 用变量和实数初始化数组

基础教程推荐