cin>>n;
int * a;
a=new int[n];
int b[n];
I think in both the cases arrays are created dynamically(correct me).So why don't we prefer 2nd case over first because 2nd is shorter and easy.
cin>>n;
int * a;
a=new int[n];
int b[n];
I think in both the cases arrays are created dynamically(correct me).So why don't we prefer 2nd case over first because 2nd is shorter and easy.
The second one does not work in standard C++. It does however work in C. Some compilers offer extensions (C++) that do allow this, but it's, again, not standard. The C++14 will come with std::dynarray which is basically what the second "way" does.
Because it is misleading.
int b[n]
is used for static array declaration. And in principle is not allowed in C++ (in case n is not constant), it is just compiler extension, which does all work for you converting int b[n]
into int *b = new int[n]
.
In such cases better to use std::vector, which is also short, but does not mislead:
vector<int> b(n);
One important difference is that the first one allocates memory in the heap and, with the proper reference, can be accessed in all the program. An should be freed once is not references (with corresponding call to delete
).
The second one allocates it in the stack and, as you can check at Why no VLAs in C++0x? this is one of main complains against VLAs. This memory is freed once you exit current block.
On the other hand, been strict, neither of them are dynamic arrays (you can't add/remove extra elements dynamically). If you want to work with dynamic arrays I would suggest using std::vector
. Although, more fitting to provided example, would be using std::array