简体   繁体   中英

How to delete this 2D Array in C++

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;
}

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;
          }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM