0

So, from what I've studied in C++, we cannot have arrays declared non-dynamically i.e. without the use of "new" keyword as it is against the C++ standard. I always thought that if not done this way, it would throw a compilation error or something and so didn't try it out myself (my bad). However, I now notice my peers using the following format of array declaration without any form of errors :

int n;
cin >> n;
int arr[n];

Now they have always been doing it this way as many of them were unfamiliar with dynamic allocation of memory or vectors and they seemingly never had an issue. Ran it on my machine for confirmation and it worked like a charm. So, my question is how does this work and if this works why bother with dynamic memory allocation? Are there some particular scenarios where this might fail badly?

9
  • 1
    FWIW, it doesn't actually work. Add the -pedantic-errors compiler option to your compile command and watch the code now fail to compile. Run time size arrays is not something that is actually a part of C++ Commented Jun 7, 2021 at 16:52
  • 1
    This is a variable length array. They are not supported in standard C++ but some compilers permit them as an extension; it seems like yours is one of them. Commented Jun 7, 2021 at 16:53
  • It is rather unfortunate the gcc (probably you are using it) is rather lax on default settings and that variable length arrays look like the simple solution (and that some infamous tutorial sites promote VLAs whenever possible). Use std::vector for dynamic arrays Commented Jun 7, 2021 at 16:53
  • Even when supported, they are absolutely not a complete substitute for dynamic memory allocation. One issue is that their lifetime is only until the function returns, so you can't pass such memory back to the caller - the compiler won't stop you from trying, but it's undefined behavior at runtime. Another is that there is typically no error checking and if you allocate more than the available stack space (usually a few megabytes), your program crashes with no possibility to recover. Commented Jun 7, 2021 at 16:55
  • If the user inputs a large enough n Automatic storage will be exhausted, Undefined Behaviour will be invoked, and technically the world could come to an end. But more likely you'll just get weird program behaviour and crashes. Commented Jun 7, 2021 at 16:59

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.