你实际上并没有扩大阵列。让我们详细看看你的代码:
int myArray[2];
myArray[0] = 0;
myArray[1] = 1;
您创建了一个包含两个位置的数组,索引从 0 到 1。到目前为止,一切都很好。
myArray[4];
您正在访问数组中的第五个元素(数组中肯定不存在的元素)。这是未定义的行为:任何事情都可能发生。你没有对那个元素做任何事情,但这并不重要。
myArray[2] = 2;
myArray[3] = 3;
现在您正在访问元素 3 和 4,并更改它们的值。同样,这是未定义的行为。您正在更改创建数组附近的内存位置,但“仅此而已”。数组保持不变。
实际上,您可以通过以下方式检查数组的大小:
std::cout << sizeof( myArray ) / sizeof( int ) << std::endl;
You'll check that the size of the array has not changed. BTW, this trick works in the same function in which the array is declared, as soon you pass it around it decays into a pointer.
In C++, the boundaries of arrays are not checked. You did not receive any error or warning mainly because of that. But again, accessing elements beyond the array limit is undefined behaviour. Undefined behaviour means that it is an error that may be won't show up immediately (something that is apparently good, but is actually not). Even the program can apparently end without problems.