通过另一个指针在类中删除指向多维数组的指针 - 如何? [英] Delete pointer to multidimensional array in class through another pointer - how?
问题描述
我有一个指向一个类的指针,它有一个指向多维数组的指针,但是当我需要或者将它设置为NULL时,我似乎不能从内存中删除它。
I have a pointer to a class, that have a pointer to a multidimensional array but I can't seem to delete it from memory when I need to or set it to NULL.
#define X 10
#define Y 10
struct TestClass
{
public:
int *pArray[X][Y];
};
// different tries, none working:
delete Pointer_To_TestClass->pArray[0][0];
delete[] Pointer_To_TestClass->pArray[0][0]
// or by simply:
Pointer_To_TestClass->pArray[0][0] = NULL;
我知道数组有数据,因为我可以在屏幕上看到结果。
也检查它是否已经为NULL,然后不尝试删除它。
I know the array has data because I can see the results on screen. Also check if it's NULL already, then doesn't try to delete it.
由于我想删除另一个指针中的指针 - 这是一个特殊的情况不同?像它删除保存另一个指针而不是指针内的指针的第一个指针(pArray是第二个指针,Pointer_To_Testclass是第一个指针)
Since I want to delete a pointer in another pointer - is this a special circumstance that works differently? Like it deletes the first pointer holding the other pointer instead of the pointer inside the pointer (pArray is the second pointer, Pointer_To_Testclass is the first pointer)
UPDATE /
我想要能够删除pArray [0] [0],而pArray [0] [1]仍然存在,如果[0] 0]不存在,它应该等于 NULL 。最主要是因为我想通过[X] [Y]值访问这个数组,以方便访问。如果[0] [0]是一个指针,则在删除时应该为NULL,因此我可以检查它是否为NULL。
I want to be able to delete pArray[0][0] while pArray[0][1] still exists and if [0][0] doesn't exist it should be equal to NULL. Most because I want to access this array by [X][Y] values for easy access. If [0][0] is a pointer, it should be NULL when deleted so I can check if it is NULL.
任何人都有任何想法?
Anyone has any ideas?
推荐答案
如果你想要一个指向< whatever>
的二维数组,类来处理它,然后把它的一个实例在你的TestClass。至于如何做,我通常使用这个顺序上的东西:
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:
// ...
};
但是,您可能需要考虑使用Boost ptr_vector
而不是 std :: vector
。
Given that you're storing pointers, however, you might want to consider using Boost ptr_vector
instead of std::vector
.
这篇关于通过另一个指针在类中删除指向多维数组的指针 - 如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!