所以这似乎是一个广泛回答的问题,但我更感兴趣的是两者之间究竟发生了什么不同的内部结构.
除了第二个示例不仅创建内存,而且还创建指向内存的指针的事实,当发生以下情况时,内存中会发生什么:
char a[5];
char b* = new char[5];
与我提出这个问题的原因更直接相关,我该怎么做
const int len = 5;
char* c = new char[len];
但不是
const int len = 5;
char d[len]; // Compiler error
编辑应该提到我在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
编辑2:应该发布我正在使用的确切代码.当使用运行时值计算动态分配的数组的常量长度时,会产生此错误.
假设random(a,b)在a和b之间返回一个int,
const int len1 = random(1,5);
char a[len1]; // Errors, since the value
// is not known at compile time (thanks to answers)
而
const int len2 = 5;
char b[len2]; // Compiles just fine