Question

According to the correct answer in Static array vs. dynamic array in C++ static arrays have fixed sizes.

However, this compiles and runs just fine:

int main(int argc, char** argv) {

int myArray[2];

myArray[0] = 0;
myArray[1] = 1;

cout<<myArray[0]<<endl;
cout<<myArray[1]<<endl;

myArray[4];

myArray[2] = 2;
myArray[3] = 3;

cout<<myArray[2]<<endl;
cout<<myArray[3]<<endl;

return 0;
}

Does this mean a static array can be resized?

Was it helpful?

Solution

You're not actually enlarging the array. Let's see your code in detail:

int myArray[2];

myArray[0] = 0;
myArray[1] = 1;

You create an array of two positions, with indexes from 0 to 1. So far, so good.

myArray[4];

You're accessing the fifth element in the array (an element which surely does not exist in the array). This is undefined behaviour: anything can happen. You're not doing anything with that element, but that is not important.

myArray[2] = 2;
myArray[3] = 3;

Now you are accessing elements three and four, and changing their values. Again, this is undefined behaviour. You are changing memory locations near to the created array, but "nothing else". The array remains the same.

Actually, you could check the size of the array by doing:

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.

OTHER TIPS

No, not a chance in hell. All you've done is illegally access it outside it's bounds. The fact that this happens to not throw an error for you is utterly irrelevant. It is thoroughly UB.

First, this is not a static array, it is an array allocated in the automatic storage.

Next, the

myArray[4];

is not a new declaration, it is a discarded read from element #4 of the previously declared 2-element array - an undefined behavior.

Assignments that follow

myArray[2] = 2;
myArray[3] = 3;

write to the memory that is not allocated to your program - an undefined behavior as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top