-1

I have a function:

void f(const size_t &len){
    double arr[len];
}

but it doesn't work, because I got message from len, that "expression must have a constant value". How can I solve this problem, if I don't want to create a global variable len?

user3840170
  • 26,597
  • 4
  • 30
  • 62
NN_05
  • 179
  • 1
  • 1
  • 8

2 Answers2

3

C++ does not support variable-length arrays. If len is a compile time constant, I'd advise you to use std::array with a template, like so:

template<size_t len>
void f(){
    std::array<double, len> arr;
    //use arr
}

And you would use it like that:

int main()
{
    f<5>();
}

Do note, that the 5 in my example is a compile-time constant. If you do not know the size of your array at compile time, use a std::vector. You'd do this like this:

void f(const size_t len){
    std::vector<double> arr(len);
    //use arr
}

int main()
{
    size_t variableLength = 0;
    std::cin >> variableLength;
    f(variableLenght);
}
divinas
  • 1,787
  • 12
  • 12
0

You need to create a Dynamic Array (On the free store). using one of the memory allocation functions.

double* arr = new double[len];

But you have to keep track of the memory release yourself!! so you have to Save your pointer as a global variable or as a class member to delete it later using

delete[] arr;
arr = nullptr;

This is how Dynamic arrays are managed in c++, but static arrays are created on the stack of an instruction block and they are destroyed automatically.And theire size must be defined at compile time not at run time.

Rahim
  • 1
  • 3
  • _But you have to keep track of the memory release yourself!_ — That's why it's so much preferred to use a `vector`. – Daniel Langr Feb 20 '20 at 10:56
  • @ Daniel Langr. Yes you are right but is very important and benefic to be familiar with memory managment. because this is the strong point in a Low level programing Language. Otherwise i would go for something else like Java or C# where all this stuff is hidden from the programmer – Rahim Feb 20 '20 at 11:00
  • _Otherwise i would go for something else like Java or C#..._ — Agree, but one isn't always so lucky to have this choice ;-). – Daniel Langr Feb 20 '20 at 11:06