数组[n] VS数组[10] - 初始化数组变量VS实数 [英] Array[n] vs Array[10] - Initializing array with variable vs real number

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

问题描述

我有我的code中的以下问题:

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

返回以下错误:
错误:可变大小的对象tenorData可能无法初始化

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

而使用双tenorData [10]工作没有任何问题。

Whereas using double tenorData[10] works without any problems.

任何人都知道为什么吗?

Anyone know why?

推荐答案

在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 int[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 函数获取大小:

constexpr int n()
{
    return 10;
}

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

这篇关于数组[n] VS数组[10] - 初始化数组变量VS实数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆