简体   繁体   English

在C ++中重新分配三维数组

[英]Deallocation of 3 dimensional array in C++

I am creating the array like this in the header file: 我在头文件中创建这样的数组:

double (*arrayName)[b][c];

And allocating it like this in the cpp file: 并在cpp文件中像这样分配:

arrayName= new double[a][b][c];

Where a, b, and c are constants based on the size of the data I am dealing with. 其中a,b和c是基于我正在处理的数据大小的常量。

How do I deallocate this array? 如何释放此数组? I tried doing the suggestion in Deallocation of 3 dimensional array , but that gives me a "Warning C4154: deletion of an array expression; conversion to pointer supplied" and causes a heap corruption error. 我尝试在三维数组的释放中执行建议,但这给了我一个“警告C4154:删除数组表达式;转换为指针提供”并导致堆损坏错误。

I'd prefer to not change to vectors as I am working with legacy code that is being repurposed but needs to stay as similar to the original as possible. 我宁愿不改变向量,因为我正在处理重新利用的遗留代码,但需要保持与原始代码类似。 I've already had to change from using static allocation to new/delete, as with the scale of the data we are working with it was overflowing the stack. 我已经不得不从使用静态分配更改为new / delete,因为我们正在使用的数据规模溢出了堆栈。

Edit: WhozCraig's method appears to be correct. 编辑:WhozCraig的方法似乎是正确的。 I thought the way I was deallocating this array (and others like it) was my problem, but I noticed another issue in my code. 我认为我释放这个数组的方式(以及其他类似的)是我的问题,但我注意到我的代码中的另一个问题。 I think I've fixed that, and I'll report back once my program is done rerunning (will take a day or two at least). 我想我已经解决了这个问题,一旦我的程序重新运行(至少需要一两天),我会报告回来。 Thanks for everyone who responded. 感谢所有回复的人。

Edit 2: Things still aren't working 100%, but the issues are outside the scope of this question and I was able to tweak some values to get things working well enough to get the job done. 编辑2:事情仍然没有100%工作,但问题超出了这个问题的范围,我能够调整一些值,以使事情运行良好,完成工作。 Thanks again for all who responded. 再次感谢所有回复的人。

The vector-delete should work for this. vector-delete应该适用于此。

static const int b = 10;
static const int c = 10;
double (*arrayName)[b][c] = NULL;
arrayName = new double[10][b][c];
delete [] arrayName;

If you must allocate this dynamically and immediately like this, and want proof that destructors are fired correctly... 如果你必须像这样动态地分配它,并希望证明解析器被正确触发...

#include <iostream>
using namespace std;

class MyObj
{
public:
    MyObj() : val(1.0) {};
    ~MyObj() { cout << "~MyObj()" << endl;}

private:
    double val;
};

int main()
{
    static const int b = 3;
    static const int c = 3;
    MyObj (*arrayName)[b][c] = NULL;
    arrayName = new MyObj[3][b][c];
    delete [] arrayName;
    return 0;
}

will result in the following output (don't bother counting, there are 27 of them) 将导致以下输出(不要打扰计数,其中有27个)

~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()
~MyObj()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM