I am trying to create an array of a size specified by a command line argument. I assign it to a const int using const int size = stoi(argv[3]);
. However when I pass this value into an object constructor someConstructor(const int size)
and I try to create an array based off that size in the construtor int table[size];
I get "expression did not evaluate to a constant". What am I doing wrong?
Asked
Active
Viewed 38 times
0

Kyle S
- 63
- 1
- 6
-
Use [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) – bolov Oct 31 '20 at 18:45
-
I cannot use a vector. I am limited to using an array for this task. – Kyle S Oct 31 '20 at 18:46
-
2You cannot use arrays like that. C++ does not work this way. You will have use `new` and `delete` to manage a dynamic array. See your C++ textbook for more information. – Sam Varshavchik Oct 31 '20 at 18:47
-
2This task is impossible with arrays in standard C++. The correct solution is to use `std::vector`. The alternate - but non-sensical in this case - is to use `std::unique_ptr
`. And the absolute worst is to use manual memory management (`new[]`/`delete[]`). – bolov Oct 31 '20 at 18:50 -
I ended up using "new". I am used to this functionality being permitted in Java. – Kyle S Oct 31 '20 at 19:54
-
If this code does matter i suggest to invest the time to understand bolov's comment and use unique_ptr (if not std::vector). Dynamic arrays can easily lead to memory leaks. Even if smart pointers are used, people tend to use the wrong template argument and create memory leaks where they do not expect them. – Mehno Nov 01 '20 at 00:21