您只分配一个指针数组item *
,您还需要为每个指针分配内存item
,例如:
struct item // naming it 'items' might be confusing, and was used inconsistently
// in your code sample
{
int member1;
int member2;
};
int N=5;
item **ptr=new item *[N];
for(int i = 0; i < N; ++i)
{
ptr[i] = new item();
}
访问您的结构成员如下所示:
ptr[2]->member1 = 42; // Sets member1 of the 3rd item element to 42
请注意,您需要在某处释放分配的内存,如下所示:
for(int i = 0; i < N; ++i)
{
delete ptr[i];
}
delete [] ptr;
我一般对于c++你最好使用 c++ 标准容器,例如:
#include <vector>
int N = 5;
std::vector<item> myItems;
myItems.resize(N,item());
myItems[2].member1 = 42; // Sets member1 of the 3rd item element to 42
它将在内部为您完成所有内存管理。
如果您使用的是c++11并且不需要动态大小的数组,您甚至可以使用以下方法完全避免堆分配内存std::array
:
#include <array>
std::array<item,5> myItems; // Size is fixed to 5, you can't use a variable here
myItems[2].member1 = 42; // Sets member1 of the 3rd item element to 42