Failed to allocate an array of pointers to a struct

倖福魔咒の 提交于 2019-12-25 19:35:20

问题


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!


回答1:


It's C++:

  • don't use malloc, use new
  • don't use plain arrays, use std::vector or std::array
  • don't use raw pointers, use std::unique_ptr



回答2:


Do not use

Bricks **   //will be a 2 dimensional array 

Use instead

Bricks *   //will be a 1 dimensioanal array

If you want a single dimensional array

Then do

`Bricks * bricks_  = (Bricks *)malloc(sizeof(Brick) * bricks_amount_ );

`

Then you can safely do without a crash

for (unsigned short int i = 0; i < bricks_amount_; i++){


bricks_[i]->handle_ = new GameObject2D(); <----------   There will not be CRASH!
}


来源:https://stackoverflow.com/questions/37378199/failed-to-allocate-an-array-of-pointers-to-a-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!