Search code examples
c++structdynamic-arrays

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:

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.