【问题标题】:Array[n] vs Array[10] - Initializing array with variable vs numeric literalArray[n] vs Array[10] - 用变量和实数初始化数组
【发布时间】:2013-02-07 09:58:21
【问题描述】:

我的代码存在以下问题:

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++ 中,这种形式的数组需要有一个编译时常量大小。
  • C++,使用带有 mingw32-g++ 编译器的代码块!
  • 谢谢,贾斯汀和@AndrewVarnerin,解决了它!在 int 之前添加 const: const int n = 10;解决了!

标签: c++ arrays initialization size


【解决方案1】:

在 C++ 中,可变长度数组是不合法的。 G++ 允许它作为“扩展”(因为 C 允许它),所以在 G++ 中(而不是 -pedantic 关于遵循 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

【讨论】:

  • 谢谢,这是另一个很好的解决方案。我最终真正需要的是一个向量而不是一个数组!
  • @msmf14:是的,像vector 这样的标准容器非常有用。
  • 调用“std::vector a(n);”时向量解是否初始化每个元素?
  • 如果你没有分配太多(如果它与堆栈大小相比很小),我更喜欢将堆栈内存与 alloca(3) 和放置 new 一起使用。这样你就不用担心释放内存了,内存分配也快了很多。
  • +1 提到 g++ 允许它。因为我没有观察到这个错误,这解释了差异。
猜你喜欢
  • 2021-09-27
  • 2020-06-15
  • 1970-01-01
  • 1970-01-01
  • 2021-06-26
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
  • 2013-08-20
相关资源
最近更新 更多