Omar Walid
Omar Walid

Reputation: 27

how can i get the size of an array so i can declare said array from a function

    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

Answers (2)

xSnailu
xSnailu

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

Kerek
Kerek

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:

  1. Declare the function arraySize as constexpr, assuming you can calculate its value at compile time, or create a constant (again, with constexpr) which represents the array size.
  2. Use dynamically allocated objects, such as 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

Related Questions