分配2-D阵列时的内存管理 [英] Memory management in allocating 2-D array

查看:115
本文介绍了分配2-D阵列时的内存管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已使用以下代码分配了一个二维数组:

I have allocated a two dimensional array using the following code:

// Dynamic allocation
        int **matrix=new int*[n];
        for(int i=0;i<n;i++)
        {
            matrix[i]=new int[n];
        }

这很好。


  • 首先,我们分配一个整数指针数组。

  • 然后,我们进一步将每个早期指针分配给指向 n 整数的内存位置。这创建了我们的二维数组。

  • Firstly we allocate an array of integer pointers.
  • Then we further allocate each of the earlier pointer to point at a memory location of n integers. This creates our two dimensional array.

我知道动态分配的数组的析构函数应该是:

I know that a destructor for a dynamically allocated array should look like:

~SquareMatrix()
{
delete [] OneDarray;
}

重点放在 [] 因为如果它不是写的,只有数组的第一个元素将被删除。

The emphasis being on [] because if it is not written, only the first element of the array will be deleted.

出于类似的原因,我想我需要放置 [] 两次,以便删除整个二维数组,如,

On similar grounds, I guess I need to place the [] twice so as to delete the entire two dimensional array, like,

delete [] [] matrix;

但这不工作,并给出编译时错误。

But this is not working and giving a compile time error.

正确的方式是什么?

推荐答案

for(int i=0;i<n;i++)
{
    delete [] matrix[i];
}

delete [] matrix

每个内部数组,然后删除数组。

You need to delete each of the internal arrays and then delete the array.

正如在注释中建议的。一个更安全的方法是使用标准容器,例如 std :: vector 。您可以这样做:

As has been suggested in a comment. A safer way of doing this would be to use standard containers such as std::vector. You could do something like this then:

std::vector<std::vector<int>> matrix;

这将给你一个二维数组,但你不必处理清理。

This would give you a two dimensional array but you would not have to handle the cleanup.

这篇关于分配2-D阵列时的内存管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆