I find it possible to initialise arrays dynamically in C++. By this i mean :
int n;
int ar[n];
works fine.
So what is the difference between this and vectors ?
I find it possible to initialise arrays dynamically in C++. By this i mean :
int n;
int ar[n];
works fine.
So what is the difference between this and vectors ?
The one thing is that VLA (and int arr[n] with n being something else than a constexpr is a variable length array) are not supported by C++ standard. So even if some compilers accept it, it is at least not portable.
The other thing is that a vector can adapt it's size dynamically, i.e. it "increases" on demand, and you can let it shrink. This is not possible with a VLA, since - once defined for a particular n, allocates memory according to n elements, and it cannot grow or shrink any more afterwards.
Further, VLA's in their typical use have a good chance to be allocated on the stack, which has a rather limited size compared to the heap. Vectors allocate memory on the heap, so they usually can get much bigger. So with VLAs you might run into memory problems for ns where you would have clearly no problem with vectors. Try, for example, int n=100000; int arr[n]; arr[100]=0 and see what happens.