+ 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.
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.
+ 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.
+ 1
Yeah I did that already. Stackoverflow tells you much more than you search for. Thanks for the considerate opinion though.
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
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.
0
It's strange that one language can work differently on different systems.