因此,这似乎是一个得到广泛回答的问题,但我更感兴趣的是两者之间到底发生了什么不同的内部情况。
除了第二个示例不仅创建内存,而且创建指向内存的指针这一事实之外, 会发生什么在记忆中当发生以下情况时:
char a[5];
char b* = new char[5];
还有更直接的关系why我问了这个问题,我怎么可以
const int len = 5;
char* c = new char[len];
but not
const int len = 5;
char d[len]; // Compiler error
EDIT应该提到我在 VC++ 上遇到了这个编译器错误(见图...)
1>.\input.cpp(138) : error C2057: expected constant expression
1>.\input.cpp(138) : error C2466: cannot allocate an array of constant size 0
1>.\input.cpp(138) : error C2133: 'd' : unknown size
EDIT 2:应该发布我正在使用的确切代码。当使用运行时值计算动态分配数组的常量长度时,会产生此错误。
假设random(a,b)
返回一个int
之间a
and b
,
const int len1 = random(1,5);
char a[len1]; // Errors, since the value
// is not known at compile time (thanks to answers)
whereas
const int len2 = 5;
char b[len2]; // Compiles just fine