c++ - 二维指针数组:删除数组但不删除指针?
问题描述
在我的代码中,我有一个指向数据的二维指针数组:
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
,所以我不确定我到底做错了什么。如何删除二维数组而不删除它保存的数据?
解决方案
推荐阅读
- java - 为什么菜单项在工具栏内的 ActionMenuView 上如此奇怪地对齐?
- php - 在php中合并行
- html - 在不影响标题文本的情况下无法移动按钮
- javascript - Codepen.io 中使用的 CoffeeScript 不再适用于 Internet Explorer
- assembly - 如何通过调试避免在琐碎指令中重定位截断?
- java - 3D HashMap java获取条目
- python - 如何枚举新列?
- python - Python中的Perl(un)pack方法
- java - 我们如何在我的条件下正确使用嵌套的 onClickListener?
- java - 具有多个逻辑运算符的三重条件 Do-While 循环