Releasing a 3-dimensional array in C ++

I create an array like this in the header file:

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

And highlighting it like this in the cpp file:

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

Where a, b and c are constants based on the size of the data I'm dealing with.

How to free this array? I tried to make a proposal in Releasing a 3-dimensional array , but it gives me β€œWarning C4154: deleting array expression, conversion to pointer” and causes a bunch of corruption error.

I would prefer not to switch to vectors, since I am working with outdated code that is repurposed, but should remain as close as possible to the original. I already had to switch from using static allocation to new / delete, because with the scale of the data we are working with, it overflowed the stack.

Edit: WhozCraig method seems correct. I thought that the way to free this array (and others like me) was my problem, but I noticed another problem in my code. I think I fixed it and I will send a report as soon as my program is executed again (it will take at least a day or two). Thanks to all who responded.

Edit 2: still not working 100%, but problems are beyond the scope of this question, and I was able to tweak some values ​​to make things work well enough to get the job done. Thanks again to everyone who answered.

+4
source share
1 answer

For this, the delete vector must work.

 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 have to distribute it dynamically and immediately, like this, and want to prove that destructors are started 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 lead to the following result (no need to count, there are 27 of them)

 ~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() 
+10
source

Source: https://habr.com/ru/post/1437434/


All Articles