2

Is there a way to zero init an array of any type with a variable size? So what I want is to apply something like this:

int results[5] = {};

to a template like this:

T results[i] = {};

When I try this, my compiler says this: 'results' declared as array of functions of type 'T ()'. When I use any fixed typename I get this error: Variable-sized object may not be initialized

Also i is a variable that is passed in when this function is called.

11
  • 4
    Variable length arrays are not supported by C++ standard. Array size must be known during compilation. So, am not sure what you are asking about. Commented Dec 19, 2019 at 21:10
  • 3
    std::vector<T> results(i); Commented Dec 19, 2019 at 21:11
  • @AlgirdasPreidžius I don't know what you mean, I used T results[i]; without any problem... Commented Dec 19, 2019 at 21:11
  • If you are using gcc as your compiler, add -pedantic to your compiler options. Commented Dec 19, 2019 at 21:12
  • 2
    @user11914177 That's the point. T results[i] is a run time sized array and those are not allowed in C++. clang and gcc by default have an extension that lets you do it, but it is non-standard behavior. By using -pedantic you turn that feature off and tell the compiler to strictly follow the C++ standard. Commented Dec 19, 2019 at 21:16

1 Answer 1

2

Variable-length arrays are non-standard in C++, and your compiler supports them as an extension. Your compiler also told you the limitations of the extension: the variable-length array may not have an initializer. As a work-around, you could do this:

int results[i];
std::fill(results, results + i, 0);

Of course, the better way is to use std::vector so you are not relying on any non-standard extensions.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.