这个解除分配正确吗? [英] Is this deallocation correct?
本文介绍了这个解除分配正确吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我分配了一个3x3 2D动态数组,如下所示:
I've a 3x3 2D dynamic array allocated as below:
int** matrix = new int* [3];
matrix[0] = new int [3*3];
for (int i = 1; i < 3; ++i)
matrix[i] = matrix[i-1] + 3;
我应该如何分配它?这是正确的吗?
How should I deallocate it? Is this correct:
delete [] matrix;
delete [] matrix[0];
或者我也应该删除matrix[1]
,[2]
推荐答案
您拥有它的方式,您应该:
The way you have it, you should :
delete [] matrix[0];
delete [] matrix;
但这是分配动态2D数组的非常常规的方式.通常,您分配一个指针数组,然后为每一行(列)分配一个实际类型的数组.
But this is a very unconventional way of allocating a dynamic 2D array. Normally you allocate an array of pointers, and then you allocate an array of your actual type for every row (column).
// allocate
int **matrix = new int*[3];
for(int i = 0; i < 3; ++i)
matrix[i] = new int[3];
// deallocate
for(int i = 0; i < 3; ++i)
delete [] matrix[i];
delete [] matrix;
这篇关于这个解除分配正确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文