Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How would I make a flexible struct inside another struct?

I’m trying to create an item and box system, where a box can have a flexible amount of items inside it (i.e. not wasting memory by making every box have 50 items, when some will have just a few). I am not quite sure how to do it.

I tried to put the Item struct inside the Box struct as a flexible array, but it doesn’t really work.

Here’s my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

struct Item {
    char name[64];
    char slot;
    int weight;
    int size;
    int dmg;
};

struct Box {
    int size;
    Item items[size];
};

int main()
{
    Item sword = { "Sword", 'W', 20, 8, 5};
    Box box = { 3, (sword, sword, sword) };
}

>Solution :

A possible solution would be to use std::vector as a dynamic-size container.

You should also use std::string for strings like name (instead of a plain char array). Among other advatages, it will remove the limit of name length of 63 characters you have now.

A minimal example initializing a box with 3 items and then adding 1 item is demonstrated below:

#include <string>
#include <vector>

struct Item {
    std::string name;
    char slot;
    int weight;
    int size;
    int dmg;
};

struct Box {
    std::vector<Item> items;
};

int main()
{
    Item sword = { "Sword", 'W', 20, 8, 5 };
    Box box;
    box.items = { sword, sword, sword }; // initialize with 3 items
    box.items.push_back(sword);          // add another item
}

Notes:

  1. Consider to encapsulate the data fields by making them private and providing accessor methods.
  2. Consider to add constructors for Item and Box, and possibly other methods like add_item for Box.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading