Reputation: 27
const int size = arraySize();
int list[size];
I get the following error:
expression must have a constant value
I know this may not be the best way to do it but it is for an assignment.
Upvotes: 1
Views: 68
Reputation: 46
Try dynamic allocation of this array.
int size = arraySize();
int* list;
list = new int [size];
It should work. In addition, there is a condensed explanation of how dynamic arrays works: DynamicMemory
PS. Remember to free memory that you dynamically allocated, when it won't be needed:
delete [] list;
Upvotes: 1
Reputation: 1110
You should know that in C++ there are no dynamically allocated arrays.
Also, const
variables are not necessarily known at compile time!
You can do one of the following:
arraySize
as constexpr
, assuming you can calculate its value at compile time, or create a constant (again, with constexpr
) which represents the array size.std::vector
(which is an "array" that can expand), or pointers. However, note that when you are using pointers, you must allocate its memory by using new
, and deallocate using delete
, which is error prone. Thus, I suggest using std::vector
.Using the first one, we get:
constexpr std::size_t get_array_size()
{
return 5;
}
int main()
{
constexpr std::size_t size = get_array_size();
int list[size];
}
which compiles perfectly.
Another thing which is nice to know is that there is std::array
which adds some more functionality to the plain constant-size array.
Upvotes: 2