0

While studying pointer in C++, I encountered "Dynamic Memory allocation in arrays" which we execute like this :

int *array_ptr {std::nullptr};
size_t size{};
cout<<"Enter the size of the array: "<<endl;
cin>>size;
array_ptr = new int [size];

But my question is we can simply accomplish this by another method which is :

size_t size{};
cout<<"Enter the size of the array: "<<endl;
cin>>size;
int array [size] {};

The second method will do the same job as the first one. Then why do we use the first method in the first place? Is it just to save the memory?

  • `int array [size] {};` is not valid in standard c++ and comes with a very big limitations for the compilers that support it as an extension to the language: [https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) In standard c++ `size` must be a compile time constant. Arrays are fixed size at compile time as far as the language says. – drescherjm Mar 06 '23 at 18:01
  • 3
    *The second method will do the same job as the first one.* -- The second method isn't C++. --*While studying pointer in C++* -- In the book you were using, you never saw syntax looking like your second method -- now you know why. – PaulMcKenzie Mar 06 '23 at 18:06

1 Answers1

8

For many reasons

  • this is not a standard part of the c++ language (it has issues)

  • the data lives on the stack and so it has limited lifetime (it will disappear when the function its declared in finishes), plus stack space is limited (typically one meg or so)

  • what happens if you suddenly realize you need more entries? Maybe you cannot ask the user in advance how many entries they need

The best solution in c++ is to use std::vector, this is dynamically growable, will automatically free its memory, plus it will do bounds checking for you either in debug builds (usually) or if you use at instead or the [] operator.


My first "use std::vector" today

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
pm100
  • 48,078
  • 23
  • 82
  • 145