使用结构和指针数组 c++

Using structures and pointer arrays c++

本文关键字:数组 c++ 指针 结构      更新时间:2023-10-16

我正在尝试将指针数组写入C++中的结构。我的主要目标是能够动态地向数组添加指针。我在使用合成器时遇到问题

  struct items
  {
    int member1;
    int member2;
  };
  int N=5;
  items **ptr=new item *[N]; // This is a ptr to an array of ptr's. Each ptr 
                             // in this array needs to point to an items struct. 

我的问题是如何从这一点开始写入结构体的对象。我知道我需要先创建它们,但我不知道该怎么做。

你只分配一个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

您可以通过ptr[i] = new items()将对象添加到数组中。您可以通过ptr[i]->member1访问items** ptr中的数据。但我强烈建议使用 stl 容器和智能指针。

首先,您必须完成分配步骤。

for(int i=0;i<N;i++)
  ptr[i]=new items;

然后,您可以使用例如以下内容访问数组:

ptr[0]->member1=123;