C ++中动态分配的结构指针数组

时间:2014-10-22 22:13:16

标签: c++ arrays pointers struct dynamically-generated

好的,我对c ++很陌生(我认为我们正在学习的是c和c ++的混合)。
我已经在我的问题中发现了很多东西,遗憾的是所有这些都在C中使用malloc。

struct A {
    int randomStuff = 0;    
};
struct B {
    int numOfA= 5;  // In reality this number is variable.
    A** arrayOfA;   
};

结构给我们。现在我需要用指针分配和填充这个数组,我猜,A指针。 < - 如果我错误的指针对我来说仍然相当复杂,请在此纠正我。

A * a1 = new A;
A * a2 = new A;
B * b = new B;
// Allocate space for the array...
b->arrayOfA = new A*[numOfA];
// Next I want to initialize the pointers to NULL
for(int i; i < b->numOfA; i++){
    b->arrayOfA[i] = NULL;
}
// In another function I would the assign a value to it
b->arrayOfA[0] = a1;
b->arrayOfA[1] = a2;

我看到它的方式是b-&gt; arrayOfA需要指向一个结构的数组......就像这样

b->arrayOfA = new A*;
A * arr[numOfA];
b->arrayOfA = arr;

我的大脑正在流血。
如何正确分配它并为其分配现有值(A结构)?

*编辑
似乎代码按预期工作,我的显示器导致了我的问题。基本上,我需要一个数组&#34; arrayOfA []&#34;我将指针放在A结构中。有效地做出这样的结果:

cout << arrayOfA[0]->randomStuff // 0 would be displayed

为0。

2 个答案:

答案 0 :(得分:1)

您可以分配一个指针数组,并为每个指针分配一个对象数组

int x = 5, y = 6;
b->arrayOfA = new A*[x]; //array of pointers
for(int i=0;i<x;i++){
    b->arrayOfA[i] = new  A[y]; //matrix (array of arrays)
}

for(int i=0;i<x;i++){
    delete[] b->arrayOfA[i]; //don't forget to free memory
}
delete[] b->arrayOfA;

答案 1 :(得分:0)

您应该只能使用矢量:

#include <vector>

int main()
{
    vector<A> vector_of_a;
    vector_of_a.push_back(a1); //store a1 in the vector
    vector_of_a.push_back(a2); //store a2 in the vector
    //...
    std::cout << "Number of A's: " << vector_of_a.size() << std::endl;
    std::cout << vector_of_a[0].randomStuff << std::endl;  //prints 0 as specified but with '.' not '->'  Objects are still on the heap, and not the stack.
}

向量中的A存储在堆上,但您不需要自己管理内存(不需要malloc / free或{{1 }} / new。 当向量超出范围时,delete个对象将被正确处理 你也得到了

您也可以将指针推送到对象,但这会降低A的实用性,因为您必须为对象执行自己的内存管理:

vector

如果你真的不想使用矢量,那么我建议你将#include <vector> int main() { A* a1 = new A(); A* a2 = new A(); vector<A> vector_of_a; vector_of_a.push_back(a1); //store pointer to a1 in the vector vector_of_a.push_back(a2); //store pointer to a2 in the vector //... std::cout << "Number of A's: " << vector_of_a.size() << std::endl; std::cout << vector_of_a[0]->randomStuff << std::endl; //prints 0 as specified //... for (auto i : vector_of_a) { delete (i); } vector_of_a.clear(); } 变成一个完全成熟的类。
它为您提供了封装的好处,管理数据的功能存储在类中,并且类执行内存管理而不会将其留给 用户管理和清理它的代码:

struct B
通过内化内存管理和支持仲裁长数组,我们刚刚开始实现一个(很多)更简单的向量版本。但有益于练习/学习。

相关问题