tags:

views:

100

answers:

2

Hi guys! I've absolutely no idea why my delete codes inside the destructor won't be able to functionally well. I hope u guys can help me for this.

Thank you so much!

class Array2D
{
      public: 
      Array2D();
      Array2D(int,  int);
      ~Array2D();

      private:
      int row;
      int col;
      int **p;
};

Array2D::Array2D()
{
      // Default Constructor
}


Array2D::Array2D(int rows, int cols)
{
     this -> row = rows;
     this -> col = cols;

     p = new int* [row]; 
     for(int i=0; i< row; i++)
          p[i] = new int[col];

     // Fill the 2D array
     for (int i = 0; i < row; i++)
          for (int j = 0; j < col; j++)
          {
               p[i][j] = rand () % 100;
          }
}    


Array2D::~Array2D()
{
     // I'm using this way to delete my 2D array.
     // however, it won't work!

     for (int i = 0; i < row; i++)
     {
          delete[]p[i];
     }
     delete[]p;
}
+3  A: 

You are not initializing anything in your default constructor. That means that the destructor will go mad on a default constructed object. You are also not disabling the copy constructor, which is not functioning with your class, because if you have copied an object, it will try to delete the same table twice. Change it as follows, for example

class Array2D
{
      public: 
      Array2D();
      Array2D(int,  int);
      ~Array2D();

      private:
      int row;
      int col;
      int **p;

      void initialize(int rows, int cols);

      // disable copy functions (make private so they cannot 
      // be used from outside).
      Array2D(Array2D const&);
      Array2D &operator=(Array2D const&);
};

Array2D::Array2D()
{
     initialize(0, 0);
}


Array2D::Array2D(int rows, int cols)
{
     initialize(rows, cols);
}    

void Array2D::initialize(int rows, int cols) {
     this -> row = rows;
     this -> col = cols;

     p = new int* [row]; 
     for(int i=0; i< row; i++)
          p[i] = new int[col];

     // Fill the 2D array
     for (int i = 0; i < row; i++)
          for (int j = 0; j < col; j++)
          {
               p[i][j] = rand () % 100;
          }

}
Johannes Schaub - litb
Thanks for your reply. I cannot modify the structure as the structure is provided by my prof. This is my homework and I get stuck in deletion part. Below is my edited given codes.
zhen
A: 

What if I'm given these?

class Array2D
{
      public: 
      Array2D();
      Array2D(int,  int);
      ~Array2D();

      private:
      int row;
      int col;
      int **p;
      void initialize ();
      void generateArray();
};
zhen
What's the problem? Have the default ctor initialize row, col, and p to 0.
Ari