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!
I know to delete a normal array in a destructor is just
delete [] foo;
how do you delete a multi-dimensional array?
Thanks!
ASKER
ohhh.. okie so like this?
char board[4][4];
for (int i = 0; i < 4; i++)
delete [] board[i];
delete [] board;
char board[4][4];
for (int i = 0; i < 4; i++)
delete [] board[i];
delete [] board;
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
>>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
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
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
}
foo *a = new foo();
is my destructor this?
foo::~foo()
{
for (int k=0; k < rowSize; k++)
{
delete [] bar[k];
}
delete [] bar
}
You first need to iterate through each item in the array, and delete it.