C ++ expression must have constant value

I have this method:

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

But he throws an error:

expression must have a constant value

I found exactly this solution:

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

so I ask, is there a better way to handle this?

+4
source share
2 answers

you can use std::vector

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

The reason your first method won't work is because the size of the array must be known at compile time ( without using compiler extensions ), so you need to use arrays of dynamic size. You can use newto distribute 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 is more useful to use std::vector.

+7
source

Built in arrays std::array . , dynamic arrays (, new) , .

std::vector (, , ) a, , array-type applications. , , , . std::vector , .

int arr[items.count]; : -

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

std::vector, 99% - . , . . , , push_back, insert, emplace_back, emplace, erase .., , , .

. this

+1

Source: https://habr.com/ru/post/1612820/


All Articles