0

Is there a way to initialize a C++ struct/class with very large array members? I would like to initialize them by filling them with any kind of data besides an empty array. The following code is defined in a dependency of mine:

#define WORSE_DATA_LENGTH 8000

struct LibraryStruct {
    int lots;
    int of;
    int fields;
    int huge_array[2000]; // how to initialize this?
    char even_worse[WORSE_DATA_LENGTH]; // how to initialize this?
};

Note that there are not any defined constructors. It should be assumed that I cannot edit this struct.

Here's the code I've tried to make use of LibraryStruct with:

int main() {
    // I can do this, but can I fill these arrays with data?
    // Say, for example:
    //  - fill huge_array with 2000 random ints 
    //  - fill even_worse with the current day of the week in 20 different languages
    const auto my_struct = LibraryStruct{5, 8, 900, {}, {}};
    return 0;
}

I've looked around and all of the examples with initializer lists with arrays that I've found have arrays with a small number of elements, and I think this example demonstrates a need for another way to initialize arrays.

karobar
  • 1,250
  • 8
  • 30
  • 61
  • 3
    `int huge_array[2000] = {};`? Initialize with what? – ChrisMM Oct 26 '21 at 18:35
  • 2
    You could consider `std::vector` instead if you are worried about a potential stack overflow. – Cory Kramer Oct 26 '21 at 18:35
  • 1
    `std::array my_array = my_array_builder();`? – Jarod42 Oct 26 '21 at 18:36
  • Initialize an array with 2000 different values? – Mitu Raj Oct 26 '21 at 18:37
  • @ChrisMM @Mitu Just fill with any values really, what I actually need to do is accept a `LibraryStruct` as a function parameter, and return a new `LibraryStruct` with a few fields changed, so `huge_array` would actually be a copy of the array field within the `LibraryStruct` given to me. I've tried to distill it down to the more fundamental issue I'm having. – karobar Oct 26 '21 at 18:47
  • @karobar So you want a copy constructor? – John Oct 26 '21 at 18:52
  • @John I don't think so, because a few of the fields should be different – karobar Oct 26 '21 at 18:54
  • Performance doesn't really depend on *how* you initialise. It depends on *whether* you initialise. If you don't need it, don"t do it. Assign individual fields. Otherwise, pick the way you think is most readable. – n. m. could be an AI Nov 10 '21 at 15:01

0 Answers0