-2

I am trying to create the array new_array of size max_value inside function something. The value of max_value can only be known at runtime. How can I fix this code?

void something (int input_array[], int array_length) {
    int max_value = *std::max_element(input_array, input_array + 8);
    int new_array[max_value] = {0};
}

I am getting the live issue message: "variable sized object may not be initialized"

Senyokbalgul
  • 1,058
  • 4
  • 13
  • 37

1 Answers1

3

C++ doesn't have variable length arrays (read here why) though some compilers may support them (and yours as well).

If you are ok with using heap instead of stack you could use std::vector like this:

std::vector<int> new_array(max_value, 0);

But to remove the error you can just remove initializer and initialize array manually like this:

int new_array[max_value];
memset( new_array, 0, max_value*sizeof(int) );
Yola
  • 18,496
  • 11
  • 65
  • 106