As an intro, I\'m using C++ in Visual Studio 2010, compiling for x64. I have a program that\'s using 2-Dimensional arrays to store data for running through a C style functio
You could use below as a macro or some delete function for 2D array with row count predefined :
for_each(results, results + rows , [](int* row) { delete[] row; });
delete[] results;
Your code crashes because you are passing an address of an address to delete[]
, which is not what you allocated. Change your code to this:
for (int i = 0; i < rows ; ++i){
delete [] results[i];
delete [] data[i];
}
It will no longer crash.
The rule on this is simple: since you assigned the results of new[..]
to results[i]
, you should be passing results[i]
, not &results[i]
, to delete []
. Same goes for data
.
Also note that this code deletes all rows that you allocated, including the last one (the loop condition is now i < n
, not i < n-1
). Thanks bjhend!