Link to home
Start Free TrialLog in
Avatar of CBMLude
CBMLude

asked on

How do you delete a multi-dimensional array?

Hi,

I know to delete a normal array in a destructor is just

delete [] foo;

how do you delete a multi-dimensional array?

Thanks!
Avatar of Axter
Axter
Flag of United States of America image

>>how do you delete a multi-dimensional array?

You first need to iterate through each item in the array, and delete it.
Avatar of CBMLude
CBMLude

ASKER

ohhh.. okie so like this?

char board[4][4];


for (int i = 0; i < 4; i++)    
    delete [] board[i];

    delete [] board;
ASKER CERTIFIED SOLUTION
Avatar of Axter
Axter
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CBMLude

ASKER

heh.. just beat you to it... thanks!
>>ohhh.. okie so like this?
>>char board[4][4];

No.
That is not a dynamic array.  That is a static variable, and you don't delete that type of variable.

Example:
int** array2d;
int     n = 100;
int     m = 50;

array2d = new int*[n]; // allocating memory for array of pointers
for(int i = 0; i < n;i++)
   array2d[i] = new int[m];

for(int k = 0; k < n;k++)
    for(int j = 0; j < m;j++) array2d[k][j] = 0;

//free memory
for(i = 0; i < n;i++) delete[] array2d[i]; //free memory for each                                                           //pointer
delete[] array2d;    //delete array of pointers
Avatar of CBMLude

ASKER

okie say I have a multidimensional array in my private section of my class.  And I just created a new object

foo *a = new foo();

is my destructor this?

foo::~foo()
{
  for (int k=0; k < rowSize; k++)
  {
    delete [] bar[k];
  }
  delete [] bar
}