无法分配指向结构的指针数组 [英] Failed to allocate an array of pointers to a struct
问题描述
这是我的结构:
struct Brick {
GameObject2D * handle_;
};
Brick ** bricks_;
这是我试图为它分配内存:
int bricks_amount_ = 10;
bricks_ =(Brick **)malloc(sizeof(Brick *)* bricks_amount_);
程序崩溃。我对它做了一个devenv来调试这里的问题,它崩溃:
for(unsigned short int i = 0; i bricks_ [i] - > handle_ = new GameObject2D(); < ---------- CRASH!
}
有任何建议吗?
PS:对不起我的英语:P
================== ==================================================== =====
[解决方案]
最后,我决定使用std :: vector原始指针:
bricks_.resize(bricks_amount_);
但我试图使malloc不同的方式,它的工作原理:
bricks_ =(struct Brick *)malloc(sizeof(struct Brick)* bricks_amount_);
或:
bricks_ = new Brick [bricks_amount_];
感谢希望帮助的人们!
这是C ++:
- 不要使用
malloc ,使用
new
- 不使用平面数组,使用
std: :vector
或std :: array
- 不使用原始指针,使用
std :: unique_ptr
I'm trying to allocate an array of pointers to a struct but there's something wrong with my code.
This is my struct:
struct Brick {
GameObject2D* handle_;
};
Brick** bricks_;
And this is how i'm trying to allocate memory for it:
int bricks_amount_ = 10;
bricks_ = (Brick**)malloc(sizeof(Brick*) * bricks_amount_);
The program crash. I've make a devenv on it to debug where's the problem and it crash on this line:
for (unsigned short int i = 0; i < bricks_amount_; i++){
bricks_[i]->handle_ = new GameObject2D(); <---------- CRASH!
}
Any suggestions?
PS: Sorry for my english :P
=========================================================================
[SOLUTION]
Finally i've decided to use std::vector instead raw pointers:
bricks_.resize(bricks_amount_);
but i've tried to make the malloc different way and it works too:
bricks_ = (struct Brick*)malloc(sizeof(struct Brick) * bricks_amount_);
or this:
bricks_ = new Brick[bricks_amount_];
Thank you to the people who wants to help!
It's C++:
- don't use
malloc
, usenew
- don't use plain arrays, use
std::vector
orstd::array
- don't use raw pointers, use
std::unique_ptr
这篇关于无法分配指向结构的指针数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!