0

Hi i am new to learning programming and C++, i just want to ask why we create dynamic arrays like this.

int size;
cin >> size;
int* arr = new int[size];

why can't i do :

int size;
cin >> size;
int arr[size];

The method without the new keyword gives me the same result, but my Teacher and Others use the method with the new keyword.

Husnain
  • 1
  • 1
  • Variable length arrays (what you use in the second snippet) are not part of standard C++. They are an extension of the specific compiler you are using. Assuming you are using GCC or Clang, add `-pedantic-errors` to your compiler invocation and it will not allow the non-standard extensions, so you aren't unintentionally getting accustomed to something that isn't part of standard C++. – user17732522 Feb 25 '22 at 00:58
  • 3
    You shouldn't use the first snippet either btw. Use `std::vector` instead of manually allocating memory with `new`. – user17732522 Feb 25 '22 at 00:59
  • In short - it's not defined in C++ standard. It may work in this particular compiler, because they implemented it as extension, but if you would for example try to compile it in Visual Studio, you would get an error. Also, this construct is rather limited. Compiler must guess how big the array might be and allocate that much memory beforehand, as well as handle the possibility of having a bigger array. Using heap allocation (like your `new` does) on the other hand is perfectly supported everywhere, it can handle gigabytes of memory and there are no shenanigans involved. – Yksisarvinen Feb 25 '22 at 01:00
  • 1
    @Yksisarvinen the compiler can put off allocating the memory for the variable on the stack until you know its size, so no guessing is necessary. – Mark Ransom Feb 25 '22 at 01:04
  • 2
    And because no guessing or foreknowledge is required, it makes an absolute hash out of the `sizeof` operator. All sorts of groovy benefits go out the window when `sizeof` is applied to a VLA. That's problem number two, in my opinion with the common VLA implementations. Problem number one is `int arr[size];` will reside in automatic storage (AKA "on the stack"), and Automatic storage tends to be very limited. if the user inputs a `size` of a few hundred thousand, the program runs a serious risk of Stack Overflow. – user4581301 Feb 25 '22 at 01:14
  • the other reason is because the second one creates an array on the stack (if it were allowed), which will disappear once the function that created it exits. – pm100 Feb 25 '22 at 02:23

0 Answers0