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
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 yourselfBut 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 ofdynamic arrays
(the one created withnew
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 toarray-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. Plusstd::vector
has many fancy functions to help you in your job.In your question you have to simply replace
int arr[items.count];
with :-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 likepush_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