2015-05-07 55 views
-3
#define NUMBER_OF_INFO 3 

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

struct address 
{ 
    int number; 
    int building; 
}; 

我具有上述結構,以及欲用於struct info一個數組分配存儲器,並且還struct info具有靈活的存儲器中,每個struct info包含一定數量的struct address,使其簡單地在這種情況下,假設每個struct info包含2 struct address(但不能改變struct info有固定的struct address數),那麼如何分配存儲器的struct info一個陣列大小NUMBER_OF_INFO,並且每個struct info含有2 struct address,以及如何釋放內存後的內存?如何動態分配存儲器,用於柔性陣列在C++

回答

2

使用std :: vector和push_back或其他東西來插入。所以你可以動態分配內存:

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

如果你不希望使用智能指針,然後分配和刪除可以像

#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++標準,那麼你可以使用一個初始化與運營商新的,例如

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