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

标签 c++ arrays pointers struct new-operator

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

  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++ 标准容器:

#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

它会在内部为你做所有的内存管理。
如果您使用 并且不需要动态大小的数组,您甚至可以使用 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

关于c++ - 使用结构和指针数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19387060/

相关文章:

c - 为什么在C语言中会发生这种情况?指针赋值不兼容

c++ - 模板静态变量

基本函数的 C 编译错误

c++ - 如何为数组类型调用新运算符

arrays - Solr Facet 将字符串拆分为多个术语。如何包含空格?

c++ - 对未知大小数组的引用的列表初始化 : is it supposed to deduce the array size?

php - 制作一个多维数组php mysql

c++ - 指向成员模板类的指针

c++ - 使用 Boost::Signals 进行 C++ 事件的完整示例

c++ - 第二个空格字符之后的字符串