Hello,
I've tried a search into this, and it gives a lot of results, yet they don't seem to work. I am just getting started in dynamic memory, and in my Space Invaders game, I have a wave class. Originally, the wave class consisted of a 2d array of 'ship' objects I have made.
Originally it was:
Ship Invader [20] [5];
Now I have changed it to:
Ship** Invader
I have a function which creates a dynamic 2d array and returns it:
1 2 3 4 5 6 7 8 9 10
|
Ship** MakeArray ( int x, int y )
{
Ship** InvaderA = NULL;
InvaderA = new Ship*[x];
for ( beta = 0; beta < x; beta++ )
{
InvaderA[beta] = new Ship [y];
}
return InvaderA;
};
|
Where x is the width and y is the height of the array.
In the constructor, I call:
Invader = MakeArray( width, height );
And that should make Invader point to a 2d array?
At the end of the constructor, I use this code to initialise a variable in the array:
1 2 3 4 5 6 7 8
|
for ( alpha = 0; alpha < height; alpha++)
{
curInRow [alpha] = 0;
for ( beta = 0; beta < width; beta++)
{
Invader [beta] [alpha].isAlive = false;
}
}
|
This seems to work, but when I call another function later on in the program, I get 'Unhandled exception at 0x010743c1 in SDL - Space Invaders.exe: 0xC0000005: Access violation writing location 0xfdfdfe51.'
This is the where the error occurs:
Invader [curInRow [0]] [numberRows-1].xpos = (float) curX;
It is the first line where Invaders is mentioned outside the constructor. The variables in the array size are just counters, and they cannot go above the defined width and height of the Invaders array (these are the same value used for the MakeArray function)
I think this means my pointer isnt actually pointing to an array, but it seemed to work in the constructor, whereas it doesn't work in this function.
In the debug window of my program, where it says Invaders, it only points to one 'ship' object, so does that have anything to do with it?
Also, because the new object is returned before it is deleted in MakeArray, can i delete the object by deleting where the pointer points to? i.e:
delete [] &Invader;
(This isn't the whole function for deleting the array)
Thanks for your time :)