使用结构和指针数组 c++
Using structures and pointer arrays c++
我正在尝试将指针数组写入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;
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '