0

I have an integer num that was read from a file. I want to create an array with the number of elements being num.

A sample code of what I want to do but doesn't work:

int num;
cin >> num;
int iarray[num];
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
J J
  • 93
  • 6
  • 6
    `std::vector ar(num);`, assuming of course you checked the return value of that read op *and* ensured `num` is a reasonable value (i.e. not negative, etc). – WhozCraig Feb 17 '13 at 00:39

2 Answers2

5

Arrays in C++ have compile-time bounds.

Use dynamic allocation instead, or a healthy std::vector wrapper around the same process.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
1

dynamic allocation being int * iarray = new int[num];

Just make sure to call delete[] iarray; at some point to free the memory.

thisisdog
  • 908
  • 1
  • 5
  • 13