0

Let's say I want to create an integer array whose size will be determined at runtime. The suggested way is

int n;
cin >> n;
int* array = new array[n];

But what's wrong if I do it this way? I mean it's got the advantages of static allocation, and the size is still dynamic!

int n;
cin >> n;
int array[n];

I couldn't find any straight forward answer. On a side note, is there any use at all of malloc() in CPP?

Eeshaan
  • 1,557
  • 1
  • 10
  • 22
  • `int array[n];` won't work with most compilers. It's a compiler extension. Even with compiler extension it's very limited usable. – Thomas Sablik Jun 26 '20 at 08:45
  • *On a side note, is there any use at all of malloc() in CPP?* It has the advantage of allocating memory without creating objects. This is *very* rarely needed in normal code, but for example `std::vector` can use that to allow preallocating memory without creating objects (`capacity() >= size()`). A call to `malloc()` should always be followed by call to [placement `new`](https://en.cppreference.com/w/cpp/language/new#Placement_new) before that memory is used in any way. – Yksisarvinen Jun 26 '20 at 08:45
  • 1
    TL;DR of Yksisarvinens comment: In non-library code, no. – 463035818_is_not_an_ai Jun 26 '20 at 08:47
  • Okay,...I think I got some idea. Thank guys! – Eeshaan Jun 26 '20 at 08:49

0 Answers0