1

How to use the the value stored in a int variable as the size of my array

eg.

int a = 40;
int b[a]; // a = 40
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Michael
  • 31
  • 1
  • This is not valid in `c++` https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard – drescherjm May 20 '19 at 11:14
  • [Variable-length arrays](https://en.wikipedia.org/wiki/Variable-length_array) are not supported in C++ (though some compilers add it as a non-portable extension). Use [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) instead. – Some programmer dude May 20 '19 at 11:14
  • 2
    That has been asked and answered many many many times. – Aykhan Hagverdili May 20 '19 at 11:23

2 Answers2

10

You can't; not in standard C++ anyway, unless a is a constexpr or const integral type with a positive value.

The best alternative is a std::vector<int> b(a);

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 2
    `constexpr` is not necessary for `a` to be a constant expression. `const int a = 40;` would be sufficient in this case. That said, I don't see a reason not to use `constexpr`. – eerorika May 20 '19 at 11:28
  • @eerorika: Yes, that's correct. – Bathsheba May 20 '19 at 12:39
5

Create an array with new[]:

int *b = new int[a];

but remember to delete it later with:

delete[] b;

A better alternative is the std container, like std::vector.

JeJo
  • 30,635
  • 6
  • 49
  • 88
Kaonnull
  • 71
  • 4