Search code examples
c++arrayszero-initialization

C++ zero init an array of templates with variable array length


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.


Solution

  • 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.