简体   繁体   中英

c++ expression must have a constant value

I have this method:

void createSomething(Items &items)
{
    int arr[items.count]; // number of items
}

But it's throwing an error:

expression must have a constant value

I found just this solution:

int** arr= new int*[items.count];

so I'm asking is there a better way how do handle this?

You can use a std::vector

void createSomething(Items &items)
{
    std::vector<int> arr(items.count); // number of items
}

The reason your first method won't work is that the size of an array must be know at compile time ( without using compiler extensions ), so you have to use dynamically sized arrays. You can use new to allocate the array yourself

void createSomething(Items &items)
{
    int* arr = new int[items.count]; // number of items

    // also remember to clean up your memory
    delete[] arr;
}

But it is safer and IMHO more helpful to use a std::vector .

Built in arrays & std::array always require a constant integer to determine their size. Of course in case of dynamic arrays (the one created with new keyword) can use a non-constant integer as you have shown.

However std::vector (which of course internally a dynamic array only) uses a is the best solution when it comes to array-type applications . It's not only because it can be given a non-constant integer as size but also it can grown as well as dynamically quite effectively. Plus std::vector has many fancy functions to help you in your job.

In your question you have to simply replace int arr[items.count]; with :-

std::vector<int> arr(items.count);   // You need to mention the type
// because std::vector is a class template, hence here 'int' is mentioned

Once you start with std::vector , you would find yourself preferring it in 99% cases over normal arrays because of it's flexibility with arrays. First of all you needn't bother about deleting it. The vector will take care of it. Moreover functions like push_back , insert , emplace_back , emplace , erase , etc help you make effective insertions & deletions to it which means you don't have to write these functions manually.

For more reference refer to this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM