-3
#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?

ratzip
  • 1,571
  • 7
  • 28
  • 53

2 Answers2

2

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;
    };
kylecorver
  • 449
  • 1
  • 4
  • 12
0

If you do not want to use smart pointers then the allocation and deletion can look like

#include <algorithm>

//...

info *persons = new info[NUMBER_OF_INFO];

std::for_each( persons, persons + NUMBER_OF_INFO,
               []( info &p ) { p.addressInfo = new address[2]; } );

//...

std::for_each( persons, persons + NUMBER_OF_INFO,
               []( info &p ) { delete [] p.addressInfo } );
delete [] persons;

If your compiler supports the new C++ Standard then you can use an initializer with operator new as for example

info *persons = new info[NUMBER_OF_INFO] {};
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335