通过另一个指针删除指向类中多维数组的指针 - 如何?

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)

更新/解释

我希望能够在 pArray[0][1] 仍然存在时删除 pArray[0][0] 并且如果 [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.

有人有什么想法吗?

推荐答案

如果你想要一个指向 <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.

这篇关于通过另一个指针删除指向类中多维数组的指针 - 如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:通过另一个指针删除指向类中多维数组的指针 - 如何?

基础教程推荐