-
Dynamic memory
I'm having problems with dynamic memory. I am trying to dynamically allocate a structure with a 3D array. Here is the parts of my code I need help with:
Code:
class map
{
private:
struct new_tile
{
...
}*tiles;
...
}
...
map::map(char *whichmap)
{
...
tiles = new new_tile[tilesacross][tilesdown][tilelayers];
...
}
It says this as the error message
54 maps.h
assignment to `map::new_tile *' from `map::new_tile (*)[((tilesdown - 1) + 1)][((tilelayers - 1) + 1)]'
-
I think it has to be something like:
Code:
tiles = new new_tile[tilesacross*tilesdown*tilelayers];
You then have to come up with some method of treating this single chunk of memory like a three dimension array of new_tile objects.
-
you can only do 1D arrays with the new keyword?
-
Yes, in one statement. It is possible to manually allocate multi-dimensional arrays but it gets pretty messy (not to mention the potential for poor performance) so it's probably just as easy to allocate on block and calculate your own offsets. Here's one way of allocating a three dimensional array -
Code:
int main()
{
int a =10;
int b =5;
int c =7;
int*** ptr = new int**[a];
for(int i=0;i<a;++i)
{
ptr[i] = new int*[b];
for(int j=0;j<b;++j)
{
ptr[i][j] = new int[c];
}
}
ptr[0][1][2] = 12313;
return 0;
}
To de-allocate you, do it the other way round (start by de-allocating the third dimension).
-
> tiles = new new_tile[tilesacross][tilesdown][tilelayers];
Are any of these parameters compile time constants?
Preferably two of them should be constants, but one would be better than none :)
Otherwise, it's as Enmeduranki wrote
-
they are not compiled, they are variables. I'm making this so the map files it reads can have different width's height's and layers for a bunch of customization.
what the heck is int*** ptr;? Does that make like three pointers or something?
-
It's a pointer to a pointer to a pointer.
Remember a int * is essentially equivalent to int [x].
A two dimensional array int [x][y] can be refered to as int **
and the three dimensional array int [x][y][z] as int ***
-
I got it to work
And if I just use delete [] tiles, will it free up the memory correctly? It compiles and runs correctly.
-
How did you allocate the memory?
-
-
:) Yes, well...
I guess what I am saying is it depends on how you allocated the memory as to whether that particular method is correct. Quite often the incorrect method will compile fine and run fine - but in fact be very very wrong.
So, if you can show the code that you used to allocate the memory - we can tell as to whether delete [] tiles is correct.