Greetings! I'm currently writing a collision detection algorithm for my game and have hit a snag. I was previously using a 500x500 array of bool's to represent pixels in the bitmap the collisions should be detected for. However, I need to be able to dynamically allocate the array to suit any bitmap regardless of dimensions. My code currently looks like this:
mask->bitmask = new bool[tw][th];
And I get a compiler error for passing a non-constant expression as an array bound. However, I need to pass a non-constant expression, since the bitmaps I'm using aren't of constant size. I need an array that won't waste memory for a 10x10 bitmap and won't fail to load on a 2000x2000 bitmap. How can I do this? Thanks for your help!
PS- mask is a struct, its declaration is below:
struct fsMask
{
int width;
int height;
bool *xclear;
bool *yclear;
bool *bitmask;
};
the bitmask is going to be the two-dimensional array, while xclear and yclear only contain true/false values to flag which rows and columns in the bitmap are completely clear and do not need to be checked for collisions.
By doing some step by step dynamic initialization, I think your problem can be solved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
struct stType{
bool** bitmask; //will need two levels of indirection for 2D arrays.
};
typedefstruct stType stType;
int main(void){
stType kat;
int mySize = 20;
kat.bitmask = (bool**)malloc(mySize * sizeof(bool*));
for(int i = 0; i < 20; i++){
kat.bitmask[i] = newbool[20];
}
//make sure to free the memory
return 0;
}
I did not test the code I posted, so I can not give an assurance that it will work. I can assure though, through logic, that the compiler will allow you to dynamically initialize an array in the above manner.
EDIT: I realized that I am doing it the wrong way. The malloc i did, will not set the first dimension fixed to 20. Sorry about that.
EDIT2: Ok, it bugged me so I went to figure it out. I am now pretty sure that's how I did dynamic allocation for 2D arrays before.