• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 282
  • Last Modified:

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!
0
CBMLude
Asked:
CBMLude
  • 4
  • 3
1 Solution
 
AxterCommented:
>>how do you delete a multi-dimensional array?

You first need to iterate through each item in the array, and delete it.
0
 
CBMLudeAuthor Commented:
ohhh.. okie so like this?

char board[4][4];


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

    delete [] board;
0
 
AxterCommented:
Example:

      for (int i = 0;i < size_of_foo;++i)
            delete [] foo[i];
      delete [] foo;
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
CBMLudeAuthor Commented:
heh.. just beat you to it... thanks!
0
 
AxterCommented:
>>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.

0
 
AxterCommented:
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
0
 
CBMLudeAuthor Commented:
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
}
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now