• Advertisement
Sign in to follow this  

Stupid Question

This topic is 4514 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ok, I,v made a 2D object array in one of my class. I define it in my .h CTiles *oMapMatrix; and when i read the size of the Array i "try" to initialise it. oMapMatrix = new CTiles[iLigne][iColonne]; But that doens't work. Why?

Share this post


Link to post
Share on other sites
Advertisement
You only specified a single layer of pointer indirection in "CTiles *oMapMatrix;". If it's to be a two dimensional array, you'll need to add another star:
CTiles** oMapMatrix;
and also allocate using a loop:
oMapMatrix = new CTiles*[iLigne];
for (int i = 0; i < iLigne; i++)
oMapMatrix = new CTiles[iColonne];


Cheers,
Twilight Dragon

Share this post


Link to post
Share on other sites
Look at this thread. It proposes a few solutions, namely the one in this thread and a more elegant version (look at Motorherp's version).


jfl.

Share this post


Link to post
Share on other sites
There are two problems here. Firstly, the obvious one already pointed out is that you declare oMapMatrix to be of type CTile *, but a 2D array needs a pointer of type CTile **.
Secondly, you can't allocate a multi-dimensional array in C++ like that - only a single array.
Think of CTile ** meaning: a pointer to an array of CTile * objects. Or - an array of arrays. Firs you must create an array of type CTile *:

int dim1=10,dim2=5;
CTile **_2DArray = new CTile* [dim1];


Then each element of this array needs to be allocated an array of CTiles:

for(int i=0;i<dim1;++i)
_2DArray = new CTile [dim2];


An important thing to rembember is when you delete this data you must do something similar: you can't just delete _2DArray as that will just delete the array of pointers, leaving all those arrays of CTiles floating about. Something like this is required:
for(int i=0;i<dim1;++i)
{
delete [] _2DArray;
}
delete [] _2DArray;


Hope this helps.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement