0

I know I can't create arrays like this:

int main () {
    int length;
    std::cin >> length;
    int array [length] = {};
}

Is there any way I can do it?

AndyG
  • 39,700
  • 8
  • 109
  • 143
matheussilvapb
  • 139
  • 1
  • 7

3 Answers3

7

Use a vector:

std::vector<int> arr(length);

This will contain length value-initialized int's.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

There are several options. You can use an STL container such as std::vector:

int lenght;
std::cin >> length;
std::vector<int> arr(length);

Or you can allocate memory dynamically:

int* arr = new int[length];
Marius Bancila
  • 16,053
  • 9
  • 49
  • 91
  • By using `std::vector` in this case one does allocate memory dynamically too. – lapk Mar 04 '14 at 22:16
  • 2
    `std::array` doesn't work. The length is a template parameter and therefore must be a compile time constant. `std::array` is a completely separate type from `std::array`. Hiding it in a `shared_ptr` doesn't make that go away (and wouldn't make much sense even if it worked). –  Mar 04 '14 at 22:18
  • Good point, thanks for the correction. – Marius Bancila Mar 04 '14 at 22:25
1

Use vector

#include <vector>

int main() {
  int length;
  std::cin >> length;
  std::vector<int> dynamic_array(length); 
}
Blaz Bratanic
  • 2,279
  • 12
  • 17