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

Array[n] vs Array[10] - Initializing array with variable vs real number(Array[n] vs Array[10] - 用变量 vs 实数初始化数组)
本文介绍了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 实数初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both(将 RGB 转换为 HSV 并将 HSV 转换为 RGB 的算法,范围为 0-255)
How to convert an enum type variable to a string?(如何将枚举类型变量转换为字符串?)
When to use inline function and when not to use it?(什么时候使用内联函数,什么时候不使用?)
Examples of good gotos in C or C++(C 或 C++ 中好的 goto 示例)
Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);(ios_base::sync_with_stdio(false) 的意义;cin.tie(NULL);)
Is TCHAR still relevant?(TCHAR 仍然相关吗?)