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?

6
  • Which compiler are you using? Commented Aug 11, 2014 at 1:55
  • 2
    Variable length arrays are C99 feature, but many C++ compiler support it as an extension. This is not an exact duplicate but the answers will end up being pretty similar. Commented Aug 11, 2014 at 1: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. Commented Aug 11, 2014 at 2: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. Commented Aug 11, 2014 at 3: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 Commented Aug 11, 2014 at 9:57

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
I don't have references, but you can Google for "C++ Variable Length Array". You can use alloca() to allocate VLA from stack though.
+1 this is correct... Dev-C++ uses GCC which provides this extension by default. See here for related gcc docs. -pedantic will inhibit this and many other extensions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.