-3

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 ?

  • 2
    Try to compile with `-Wall -pedantic` and the difference should be clear :) – Rakete1111 Aug 19 '17 at 18:20
  • 4
    Variable Length Arrays are not standard C++ but appear to be supported as an extension by your compiler. – Captain Obvlious Aug 19 '17 at 18:21
  • 1
    Variable length arrays are not part of standard C++. Some compilers support them as an extension to the language, but don't rely on that. – Jesper Juhl Aug 19 '17 at 18:23
  • 2
    Variable Length Arrays, even when supported, have a good chance to be allocated on the stack, which has limited size; try `int n=100000; int arr[n]; arr[100]=0` and see what happens. – Stephan Lechner Aug 19 '17 at 18:25

1 Answers1

0

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.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
  • I don't think most modern desktops are going to have a problem allocating 100000 ints on the stack. Some could even handle a million, though most would choke on 10 million. – Benjamin Lindley Aug 19 '17 at 18:44