Error declaring array

closed account (jEb91hU5)
I'm getting a compiler error when trying to initialize this array. It says I'm not able to use the variable as a constant. I'm not sure how to resolve this. Any feedback would be appreciated.

1
2
3
4
  int n, c;

    cin >> n >> c;
    int arr[n]; //error is here 


Edit: I believe I meant to say declaring the size of the array. That is what I’m having issues on.

Edit2: swapped out array for a vector.
Last edited on
array must be a compile time constant. vector is correct way to have the size at run-time.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <vector>

int main()
{
   // get a size for the vector
   std::cout << "Enter the vector's size (positive integer only): ";
   unsigned v_size { };
   std::cin >> v_size;

   // create a vector sized to the user input
   std::vector<int> vec(v_size);

   // let's see if the vector was properly created
   std::cout << "\nThe vector's size is " << vec.size() << '\n';

   // let's loop through the vector's elements, using a range-based for loop
   for (const auto& itr : vec)
   {
      std::cout << itr << ' ';
   }
   std::cout << '\n';
}
Enter the vector's size (positive integer only): 5

The vector's size is 5
0 0 0 0 0
Topic archived. No new replies allowed.