2
  int x;
    cin>>x;
    int arr[x];

The code must not compile because the program will try allocate a unknown memory for the array on the stack, BUT IT COMPILES! i know what dynamic memory is, i've read a lot about this but i don't understand , why does the program above runs?! shouldn't it be this way? :

int x;
cin>>x;
int *arr=new arr[x];

could someone plz give me an example in which does not work with static allocating and works only with dynamic allocating?

Alex Pana
  • 253
  • 2
  • 10
user3927214
  • 67
  • 2
  • 3
  • 9
  • Which compiler are you using? – R Sahu Aug 11 '14 at 01:55
  • 2
    Variable length arrays are [C99 feature, but many C++ compiler support it as an extension](http://stackoverflow.com/questions/21273829/does-int-size-10-yield-a-constant-expression). This is not an exact duplicate but the answers will end up being pretty similar. – Shafik Yaghmour Aug 11 '14 at 01:59
  • While, this is not ok in c. Why in modern language such as c++ and java is ok? I dont think it is in compiler. – paul Aug 11 '14 at 02:01
  • It will compile because the syntax is correct. This is how you declare an array, however to allocate memory, you use either "NEW" or malloc. Can you try adding elements into the array. – Juniar Aug 11 '14 at 03:29
  • OMG!!! if this is possible, then I don't understand, y do we in first place need dynamic memory allocation. This is also kind of dymanic memory allocation(only diff is that memory will be allocated from stack). Could anyone please enlighten me on this confusion? Thanks – instance Aug 11 '14 at 09:57
  • @instance because the stack is a limited resource and trying to allocate a large object on the stack will cause a [stackoverflow](http://stackoverflow.com/questions/20234048/stack-overflow-error-in-c-program/20234082#20234082). – Shafik Yaghmour Aug 11 '14 at 12:19

1 Answers1

4

Some compilers may enable using dynamic size for arrays allocated from stack. It's not standard C++ though.

JarkkoL
  • 1,898
  • 11
  • 17
  • I dont think it is in compiler. Can you site some references to clarify this? thanks, it will be of great help for me too. – paul Aug 11 '14 at 02:02
  • I don't have references, but you can Google for "C++ Variable Length Array". You can use `alloca()` to allocate VLA from stack though. – JarkkoL Aug 11 '14 at 02:15
  • +1 this is correct... Dev-C++ uses GCC which provides this extension by default. See [here for related gcc docs](https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html). `-pedantic` will inhibit this and many other extensions. – Tony Delroy Aug 11 '14 at 02:44