Search code examples
c++arraysdynamic-memory-allocation

Size of an array which is in static memory can be changed during run time in C++? How come?


I have read this paragraph from here: http://www.cplusplus.com/doc/tutorial/dynamic/

You could be wondering the difference between declaring a normal array and assigning dynamic memory to a pointer, as we have just done. The most important difference is that the size of an array has to be a constant value, which limits its size to what we decide at the moment of designing the program, before its execution, whereas the dynamic memory allocation allows us to assign memory during the execution of the program (runtime) using any variable or constant value as its size.

But this code of mine works just fine:

int number;
cin>>number;
int myArray[number];

cout<<sizeof(myArray)/sizeof(myArray[0])<<endl;
cout<<sizeof(myArray)<<endl;

Does this mean the array is created in dynamic memory? Or is it created in static memory but the size of it still determined in runtime?


Solution

  • As I pointed out in a comment, but here with more detail.

    In standard C++ the size of an array has to be known at compile time. In your example this is not the case. Your code compiles because you are (presumably) using gcc with the variable length array extension enabled.

    Setting your warning level correctly will prevent this code from compiling.