Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

c++ - Failed to allocate an array of pointers to a struct

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...