2

What I want to do is make a struct that has an array of another struct, and I want to set the size of the array at runtime. Is there any way to do that? Struct is like:

struct MyStruct
{
  AnotherStruct list[];
  int key;
  bool isLeaf;
}
Ivan Kukic
  • 425
  • 4
  • 13
  • 5
    `std::vector list;` – PaulMcKenzie Nov 26 '18 at 02:28
  • Please post this as an answer so I can mark it as a correct answer. – Ivan Kukic Nov 26 '18 at 02:32
  • Possible duplicate: https://stackoverflow.com/questions/7641698/allocating-struct-with-variable-length-array-member or https://stackoverflow.com/questions/19969438/compliant-variable-length-struct-in-c – Jerry Jeremiah Nov 26 '18 at 02:39
  • @IvanKukic Forgot to mention -- You need to post `AnotherStruct` before recommending to place it in a vector. If it has correct copy semantics, then yes, `std::vector` is safe to use. – PaulMcKenzie Nov 26 '18 at 02:55
  • @JerryJeremiah both of those questions, the answers are overcomplicated for this scenario (they assume the author didn't just want to use a vector) – M.M Nov 26 '18 at 02:57

1 Answers1

4

One way is:

#include <vector>

struct MyStruct
{
    std::vector<AnotherStruct> list;
    int key;
    bool isLeaf;
};

If you are new to vectors you can read about how to use them in any C++ reference.

M.M
  • 130,300
  • 18
  • 171
  • 314
  • I think he wants to avoid storing an extra pointer and size variable, like `std::vector` does. – Kostas Nov 26 '18 at 03:06
  • I decided to go with this approach, checking if the vector has more elements than I want it to have at the time of adding elements to it. – Ivan Kukic Nov 26 '18 at 03:21
  • 1
    @GillBates I didn't get that impression from the question, the requirements were stated fairly clearly in the first sentence. At any rate, it's not a bad approach to get the code working using straightforward code at first, and if you want to optimize for memory usage you can do that afterwards at a point where you're ready to profile and compare – M.M Nov 26 '18 at 03:25