Archived

This topic is now archived and is closed to further replies.

amish1234

best way to delete a 2d array?

Recommended Posts

I start out with:
  
char **TwoDArray;
**TwoDArray = new *char[size];
for(int i=0; i<size; i++)
{
   TwoDArray[i] = new char[size2];
}
  
Is the following the proper way to delete it?
  
for(int i=0; i<size; i++)
{
   delete [] TwoDArray[i];
}
delete [] TwoDArray;
  
Proceeding on a brutal rampage is the obvious choice.

Share this post


Link to post
Share on other sites
Yes, that''s pretty much the only way you can do it if you are allocating your "multidiensional array" in that manner.

To be honest, you''re better off not working with multidimensional arrays like that though. That forces longer construction, longer destruction, more memory for pointers, and fragmented memory.

You''re better off allocating all of the data in one strip, then overloading operators to deal with the data as a two dimensional array.

For instance -- say you want a 4 by 5 multidimensional array.

Allocate an array of length 20 (which is 4 times 5), then overload operator() to take 2 parameters (a row and a column), then define the function to return a reference to the element at the location ( row * numberofcolums + column ).

No you can allocate and deallocate all of the memory in one single statement without having to loop. This is actually how multidimensional arrays are created internally in c/c++ anyways.

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
char **TwoDArray;
**TwoDArray = new *char[size];
for(int i=0; i<size; i++)
{
TwoDArray = new char[size2];
}

That does not create a 2D array, it creates a 1D array of pointers to chars. Rethink what you are trying to do.

Share this post


Link to post
Share on other sites
Do what Matt said, make a class, and overload operator[] to return a char* to the appro. location in the memory block and you can use it as a drop-in replacement for a 2D static array.

quote:
Original post by Anonymous Poster
That does not create a 2D array, it creates a 1D array of pointers to chars. Rethink what you are trying to do.

It has the same usage syntax & semantics of a 2D static array, although you are correct that the memory layout is different.

Share this post


Link to post
Share on other sites