0
我读C++入门加上阵列,它说设置ARRAYSIZEC++阵列,在运行时
typeName arrayName[arraySize];
//Arraysize cannot be a variable whose value is set while the program is running"
不过,我写了一个程序
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int array[n];
for(int i=0; i<n; i++)
{
cout<<array[i]<<endl;
}
}
,它工作正常以下,我可以在运行时设置数组的大小。我没有收到任何编译错误,或运行时崩溃。
有人可以解释发生了什么?
由于
这不再只是一个编译器扩展,而是C99标准的一部分,它允许在堆栈上使用可变大小的数组。 (另请参阅https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html) – Florian
@Florian C++不包含所有的C99。在任何版本的C++ – NathanOliver
中,VLA都不是标准,这让我感到惊讶,但你是对的。但实际上,如果你需要C++中的VLA,反正你会使用vector <>,不会吗? – Florian