如何在C++中为灵活数组动态分配内存

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;
};

我有上面的struct,我想为struct info的数组分配内存,而且struct info有一个灵活的内存,每个struct info包含一定数量的struct address,为了简单起见,在这种情况下,假设每个struct info包含2个struct address(但不能改变struct info有固定数量的struct address),那么如何为大小为 NUMBER_OF_INFOstruct info 数组分配内存,每个 struct info 包含 2 struct address,之后如何释放内存?

如果你不想使用智能指针那么分配和删除可以像这样

#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;

如果您的编译器支持新的 C++ 标准,那么您可以使用带有 operator new 的初始化程序,例如

info *persons = new info[NUMBER_OF_INFO] {};

使用std::vector 和push_back 或其他东西插入。所以你可以动态分配内存:

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