【发布时间】:2012-03-21 20:56:37
【问题描述】:
可能重复:
C/C++: Array size at run time w/o dynamic allocation is allowed?
在下面的清单中,buf 的大小显然是由运行时常量j 决定的。
编译器如何生成代码在栈上分配存储空间(编译时不知道j的值)?
#include<iostream>
#include<cstdlib>
using namespace std;
int main(){
srandom(time(NULL));
int i = random();
cout<< "random number: "<<i<<endl;
if(i%2==0)
i=2;
else
i=1;
const int j=i;
char buf[j];
std::cout<<"size of buf array: "<<sizeof(buf)<<endl;
return 0;
}
【问题讨论】:
-
让我猜猜……你是用 g++ 编译的吗?这是允许 C99 的 VLA 的非标准扩展。 C++ 不允许它们。使用 -pedantic 和/或 -Wall 编译
-
objdump -d -S my_file如果您想查看编译器为该行生成的代码。此外,-pedantic(假设 g++):warning: ISO C++ forbids variable length array ‘buf’ -
没错!收到了
-pedantic的警告,但没有收到-Wall的警告。
标签: c++