Destructor for 2-d dynamically allocated array

I don't think my destructor is right. Can someone help me?

1
2
3
4
5
6
7
8
9
10
  // constructor code
  int **array = new int*[capacity + 1];

  for(int i = 0; i < capacity + 1; i++)
    array[i] = new int[2];

  // destructor code
  for(int i = 0; i < capacity + 1; i++)
    delete [] array[i];
  delete [] array;


It's hard finding information online about multidimensional dynamically allocated array destruction.
Does it not work properly? It looks okay to me (though I hardly every use multi-dimensional arrays).
Well, my program compiles. I'm not exactly sure how to check if my destructor is working. I sort of guessed when I made the destructor.
closed account (1yR4jE8b)
Looks fine to me, but yeah...2D Arrays are evil. It's better to just wrap an m * n 1D array in a class and just overload the operator() to get the correct elements.
What @darkestfright said. You need to declare the array with width*height elements and make an accessor function, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
struct array_2d{
	int width;
	int height;
	myType* array;//you could use a template for this
	array_2d(int w,int h){
		width=w;
		height=h;
		array=new myType[w*h];}
	~array_2d(){
		delete[] array;}
	myType& operator()(int x,int y){
		return array[y*width+x];}};//this is the accessor formula
Last edited on
Topic archived. No new replies allowed.