I want to allocate an array of struct pointers, then initialize all the pointers. it is actually a 2D array, but I'm allocating a 1D array, and handling the offset manually. Here's what I have:
// declaration of pointer to array
Bitmap** clone ;
// creation of the array of pointers
clone = new Bitmap *[tiles_x * tiles_y] ;
// allocating the struct elements (not working)
//********************************************************************
void gdi_plus::alloc_clone_elements(void)
{
uint row, col ;
for (row=0; row<tiles_y; row++) {
for (col=0; col<tiles_x; col++) {
uint toffset = (row * tiles_x) + col ;
INT xsrc = col * sprite_dx ;
INT ysrc = row * sprite_dy ;
Bitmap* tclone = gbitmap->Clone(xsrc, ysrc, sprite_dx, sprite_dy,
PixelFormatDontCare);
*(clone[toffset]) = tclone ; // this fails - Why??
// *(clone + toffset) = tclone ; // this succeeds
}
}
}
Am I even doing this correctly? I understand C/C++ enough to know that just getting it to compile without warnings doesn't actually mean that you are doing it right. And why is
*(clone[toffset]) = tclone ;
wrong, when
*(clone + toffset) = tclone ;
is okay?
I am using MinGW 32-bit (V10.3.0) on Windows 10.
*(clone + toffset)
is the same as clone[toffset]
. What you now have in your program, *(clone[toffset])
, is the same as **(clone + toffset)
.
So, if *(clone + toffset)
works, so will clone[toffset]
.
You may also want to skip manually managing memory and use a std::vector<Bitmap*>
instead:
std::vector<Bitmap*> clone;
clone.resize(tiles_x * tiles_y);
or create it with the right size at construction:
std::vector<Bitmap*> clone(tiles_x * tiles_y);
or store smart-pointers if you want to automatically deallocate the Bitmap
s when the vector
is destroyed:
std::vector<std::unique_ptr<Bitmap>> clone;