+ 1

Does C++ supports array initialization at runtime just like in Java?

Does C++ supports taking n from user input and using it to declare an array of size n? Eg: cin >> n; int arr[n]; Actually I found everywhere on the Internet that this method shouldn't work but it actually works on my codeblocks. What didn't work was this int arr[n] = {}; But this {} worked on the online available compilers like repl.it and codechef.

24th Nov 2017, 6:37 AM
Maaz
Maaz - avatar
6 odpowiedzi
+ 2
My linux box too accepts the variable length arrays and I once had an argument with my teacher about it. He claimed that the C++ standard prohibits using variable length arrays, but when I googled, it turned out that it is compiler dependent and the version of g++ I was using supported variable length arrays.
28th Jan 2018, 7:27 PM
Payal
Payal - avatar
+ 1
In c++ local variables are created on the stack and the size needs to be known at compile time. As such, you can't do "int arr[n]". Instead you do "int *arr = new int[n]". This creates the variable on the heap at runtime so it can have an unknown size at compile time.
24th Nov 2017, 7:35 AM
Tim W
Tim W - avatar
+ 1
Yeah I did that already. Stackoverflow tells you much more than you search for. Thanks for the considerate opinion though.
28th Jan 2018, 7:41 PM
Payal
Payal - avatar
0
As per the standard variable length arrays are not supported without using dynamic memory. The preferable modern C++ way is to use a container such as vector from the standard library
24th Nov 2017, 8:16 AM
aklex
aklex - avatar
0
None of these answer the question as to why this also works on online compilers like repl.it and codechef. And why int arr[n] = {}; doesn't work on codeblocks but work on online compilers.
24th Nov 2017, 8:52 AM
Maaz
Maaz - avatar
0
It's strange that one language can work differently on different systems.
24th Nov 2017, 9:04 AM
Maaz
Maaz - avatar