Array[n] vs Array[10] - Initializing array with variable vs real number(Array[n] vs Array[10] - 用变量 vs 实数初始化数组)
问题描述
我的代码存在以下问题:
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++ 中(无需 -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 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] - 用变量 vs 实数初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Array[n] vs Array[10] - 用变量 vs 实数初始化数组
基础教程推荐
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01