3

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?

Lol4t0
  • 12,444
  • 4
  • 29
  • 65
Koray Tugay
  • 22,894
  • 45
  • 188
  • 319

2 Answers2

5

The code you posted doesn't work according to the C++ standard. Since variable length arrays are popular in C, the C++ compiler implementers may have decided that it is a good idea to make this feature available in C++, too. It certainly isn't a good idea to do it as it is done in C but some variations are being discussed for inclusion into C++.

It seems, gcc and clang accept the above code (after adding the necessary includes, a function, etc.). clang even does so without a warning.

Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
  • +1 he he, no surprise that the dang compiler accepts it when g++ does. dang appears to be just be g++ clone (except that dang reportedly still fails to implement proper exception handling in Windows). – Cheers and hth. - Alf Nov 24 '12 at 21:01
  • @Cheersandhth.-Alf The fact that clang is so compatible with gcc makes it so popular, because there is close to zero overhead in porting involved. – pmr Nov 24 '12 at 21:02
5

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.

pmr
  • 58,701
  • 10
  • 113
  • 156