Advertisement

Multidimensional arrays

Started by March 19, 2000 06:23 AM
1 comment, last by null_pointer 24 years, 7 months ago
I''m using a multidimensional array to store the tiles for a map, in my map editor. I have working code to use a single dimensional array to store the tiles, but I read the thread about dynamic allocation, and decided to try it. Unfortunately, I cannot seem to delete the array! Here''s how I allocate the array: // Create a new array of tile and object pointers m_pTiles = (Tile***) malloc(dwTiles * (sizeof( Tile* ))); // Fill the array with new tile objects for( int x=0; x < m_nWidth; x++ ) for( int y=0; y < m_nHeight; y++ ) m_pTiles[x][y] = new Tile(x, y, this); And here''s how I delete it: for( int x=0; x < m_nWidth; x++ ) { for( int y=0; y < m_nHeight; y++ ) { delete m_pTiles[x][y]; // crashes here, when x=1 and y=0 m_pTiles[x][y] = NULL; } } free(m_pTiles); m_pTiles = NULL; As commented in the previous code section, the for loops delete the first column, and then crashes. In the debugger, m_pTiles[0][0] has the same address as m_pTiles[1][0]!! So, I would assume that something is wrong with my for loops. This is so frustrating! Thanks in advance for responding Thanks! - null_pointer
What does it mean when you have three stars for the pointer, like Tile***. I''ve seen several places, but don''t understand it. Also, what does something like Tile** mean? Thanks in advance.

"When people tell you they want to hear the truth, you know that their lying."
Advertisement
null_pointer:
It looks like you aren''t allocating memory for your second indirection level. Also, please don''t mix malloc''s and new''s in the same program!

typedef Tile * pTile;typedef pTile * ppTile;typedef ppTile * pppTile;pppTile tile_array;tile_array = new ppTile[m_nWidth];for(int i = 0; i < m_nWidth; i++) {  tile_array = new pTile[m_nHeight];<br>  for (int j = 0; j < m_nHeight; j++) {<br>    tile_array[ j ] = new Tile(x, y, this);<br>  }<br>}<br> </pre> <br>The to delete:<br><pre><br>for (int i = 0; i < m_nWidth; i++) {<br>  for (int j = 0; j < m_nHeight; j++) {<br>    delete (tile_array[ j ]);<br>  }<br>  delete [] (tile_array);<br>}<br>delete [] tile_array;<br> </pre> <br><br>Cloxs:<br>Tile * is a pointer to a Tile<br>Tile ** is a pointer to a pointer to a Tile<br>Tile *** is a pointer to a pointer to a pointer to a Tile<br><br>    

This topic is closed to new replies.

Advertisement