首页 > 解决方案 > 二维指针数组:删除数组但不删除指针?

问题描述

在我的代码中,我有一个指向数据的二维指针数组:

Data***

我不使用数组表示法的原因是因为大小不是在编译时确定的。所以,在我的代码的某个地方,我分配了所有必要的空间:

arr = new Data **[xVals];
for (int i = 0; i < xVals; i++)
{
    arr[i] = new Data *[yVals];
    for (int j = 0; j < yVals; j++)
    {
        arr[i][j] = nullptr;
    }
}

然后稍后用我正确的指针填充数组。此外,指针还存储在 a 中std::vector

for(...) {
    for(...) {
        // Conditional statement; not the whole array gets filled, some parts stay nullptr
        ...
        arr[xCoord][yCoord] = new Data(...);
        myVector.push_back(arr[xCoord][yCoord]);
    }
}
... // Do some other stuff that takes advantage of the spatial properties of the 2D array

使用完二维数组后,我想删除它,但不删除数据指针本身,因为它们现在存储在我的向量中。我一直在尝试以下方法:

for (int i = 0; i < xVals; i++)
{
    // Delete all "column" arrays
    delete[] arr[i];
}
// Delete 
delete[] arr;

但是,我得到一个损坏的堆错误CRT detected that the application wrote to memory after end of heap buffer,所以我不确定我到底做错了什么。如何删除二维数组而不删除它保存的数据?

标签: c++arrayspointersmemory-managementheap-memory

解决方案


推荐阅读