Failed to allocate an array of pointers to a struc

2019-09-21 19:07发布

问题:

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!
}