Search code examples
c++arraysmemorydynamic-allocation

how to dynamically allocate memory for flexible array in C++


#define NUMBER_OF_INFO    3

struct info
{
   int name;
   int age;
   struct address* addressInfo;
};

struct address
{
   int number;
   int building;
};

I have the above struct, and I want to allocate memory for a array of struct info, and also struct info has a flexible memory, each struct info contains certain number of struct address, to make it simply in this case, assume each struct info contains 2 struct address(but can not change the struct infohas fixed number of struct address), then how to allocate the memory for a array of struct info with size NUMBER_OF_INFO, and each struct info contains 2 struct address, and how to free the memory after that?


Solution

  • Use std::vector and push_back or something to insert. So you can dynamically allocate the memory:

        struct info
        {
           int name;
           int age;
           std::vector<address> addressInfo;
        };