2-Dimensional array deallocation

后端 未结 2 1888
遇见更好的自我
遇见更好的自我 2020-12-11 22:41

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

相关标签:
2条回答
  • 2020-12-11 23:00

    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;
    
    0 讨论(0)
  • 2020-12-11 23:06

    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!

    0 讨论(0)
提交回复
热议问题