Delete pointer to multidimensional array in class through another pointer - how?

孤街浪徒 提交于 2019-11-27 16:27:10

If you want a 2D array of pointers to <whatever>, create a class to handle that, then put an instance of it in your TestClass. As far as how to do that, I'd generally use something on this order:

template <class T>
class matrix2d {
    std::vector<T> data;
    size_t cols;
    size_t rows;
public:
    matrix2d(size_t y, size_t x) : cols(x), rows(y), data(x*y) {}
    T &operator()(size_t y, size_t x) { 
        assert(x<=cols);
        assert(y<=rows);
        return data[y*cols+x];
    }
    T operator()(size_t y, size_t x) const { 
        assert(x<=cols);
        assert(y<=rows);
        return data[y*cols+x];
    }
};

class TestClass { 
    matrix2d<int *> array(10, 10);
public:
    // ...
};

Given that you're storing pointers, however, you might want to consider using Boost ptr_vector instead of std::vector.

#define X 10
#define Y 10

struct TestClass
{
public:
  TestClass()
  {
    // Must initialize pArray to point to real int's otherwise pArray
    // will have bogus pointers.
    for (size_t y = 0; y < Y; ++y)
      {
    for (size_t x = 0; x < X; ++x)
      {
        pArray[x][y] = new int;
      }
      }
  }

  int      *pArray[X][Y];
};

int main()
{
  TestClass *Pointer_To_TestClass = new TestClass;
  delete Pointer_To_TestClass->pArray[0][0];
  Pointer_To_TestClass->pArray[0][0] = 0;
  return 0;
}

Depends on your allocation of pArray[i][j]. If it's something like pArray[i][j] = new int; then call delete Pointer_To_TestClass->pArray[0][0];. If it's something like pArray[i][j] = new int[10] then use your second option, delete[] Pointer_To_TestClass->pArray[0][0];. I'd also highly recommend immediately following the delete with setting it to NULL and proceeding it with the check for NULL.

The third one did not compile for me delete[][] Pointer_To_TestClass->pArray[0][0]; I got the error

Line 34: error: expected primary-expression before '[' token compilation terminated due to -Wfatal-errors.

Also, I'd highly recommend having those deletes in the destructor. Other places may be fine as well.

You may find the typedef of int* to be helpful for readability understanding you have a two-dimensional array of int*.

If you've dynamically created an array, then delete it with delete[]. You have to give delete[] a pointer to the start of the array, however, not an element of the array!

If you want the elements to be deletable, then they have to be dynamically allocated separately.

So you have to have a multi-dimensional array of pointers;

int *(*pArray)[X][Y];

Then dynamically assign each one, which yes is a pain.

It is interesting, however, that you are even attempting to do this, why do you want to delete single elements?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!