Search code examples
c++templatesstdarray

How to fix compiler error when try to initialise a std::array from a non const size


I know I can use a vector, but I don't need the extra features of a vector so wanted to use a std::array. The problem I have is that I get the size of the array from the user - from stdin. Then I know the size and initialise the array from there.

I tried the following code but get the compiler error as shown. I also tried constexpr with fsize.

How can I edit my code to create a std::array from a size not known at compile time?

int main() {

  int size;
  cin >> size;

  const int fsize = size;
  // below line compile error
  std::array<int, fsize> items;
}

compile error:

error C2971: 'std::array' : template parameter '_Size' : 'fsize' : a local variable cannot be used as a non-type argument
 : see declaration of 'std::array'
   see declaration of 'fsize'

Solution

  • How can I edit my code to create a std::array from a size not known at compile time?

    You can't. std::array is a fixed-sized array, it's size must be a constant known at compile-time.

    To make a dynamic array whose size is not known until runtime, you must use new[] instead:

    int *items = new int[fsize];
    ...
    delete[] items;
    

    Preferably, you should use std::vector instead, which handles that for you:

    std::vector<int> items(fsize);
    

    If you don't want to use std::vector, you can use std::unique_ptr<int[]> instead:

    std::unique_ptr<int[]> items(new int[fsize]);
    

    or

    auto items = std::make_unique<int[]>(fsize);