Search code examples
c++arraysstatic-array

C++ / Is it allowed to change size of an static array or not?


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?


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.