我知道C99之前的C标准(以及C++)说堆栈上的数组大小必须在编译时知道.但那是为什么呢?堆栈上的数组在运行时分配.那么为什么大小在编译时很重要?希望有人向我解释编译器在编译时将如何处理大小.谢谢.
这种数组的例子是:
void func()
{
/*Here "array" is a local variable on stack, its space is allocated
*at run-time. Why does the compiler need know its size at compile-time?
*/
int array[10];
}
Run Code Online (Sandbox Code Playgroud) 我一直认为在C++中声明一个数组时,大小必须是一个常量整数值.
例如 :
int MyArray[5]; // correct
Run Code Online (Sandbox Code Playgroud)
要么
const int ARRAY_SIZE = 6;
int MyArray[ARRAY_SIZE]; // correct
Run Code Online (Sandbox Code Playgroud)
但
int ArraySize = 5;
int MyArray[ArraySize]; // incorrect
Run Code Online (Sandbox Code Playgroud)
以下是Bjarne Stroustrup在C++编程语言中的解释:
数组的元素数量(数组绑定)必须是常量表达式(§C.5).如果需要变量边界,请使用向量(§3.7.1,§16.3).例如:
void f(int i) {
int v1[i]; // error : array size not a constant expression
vector<int> v2(i); // ok
}
Run Code Online (Sandbox Code Playgroud)
但令我惊讶的是,上面的代码在我的系统上编译得很好!
这是我试图编译的内容:
void f(int i) {
int v2[i];
}
int main()
{
int i = 3;
int v1[i];
f(5);
}
Run Code Online (Sandbox Code Playgroud)
我没有错!我正在使用GCC v4.4.0.
有什么我想念的吗?