删除动态分配的2D数组 [英] Deleting a dynamically allocated 2D array

查看:78
本文介绍了删除动态分配的2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我习惯于在C中进行内存管理,其中free(pointer)将释放pointer指向的所有空间.现在,当我尝试用C ++做一些简单的事情时,我感到困惑.

So I'm used to memory management in C where free(pointer) will free up all space pointed to by pointer. Now I'm confusing myself when attempting to do something simple in C++.

如果我以类似的方式分配了一个二维双精度数组

If I have a 2D array of doubles allocated in a manner similar to this

double** atoms = new double*[1000];
for(int i = 0; i < 1000; i++)
  atoms[i] = new double[4];

释放new分配的堆上的内存的正确方法是什么?

what would be the correct method of freeing the memory on the heap allocated by new?

我的最初想法是这样的(因为我的大脑在用C语言思考):

My thoughts were originally this (because my brain was thinking in C):

for(int i = 0; i < 1000; i++)
  delete atoms[i];
delete atoms;

但是我忘记了delete[]运算符的存在,所以我相信正确的方法如下:

But I had forgotten the existence of the delete[] operator so I believe the correct method is as follows:

for(int i = 0; i < 1000; i++)
  delete[] atoms[i];
delete[] atoms;

了解deletedelete[]运算符之间的区别是否重要?还是可以假设我每次使用ptr = new x[]分配数组时也必须使用delete[] ptr取消分配它?

Is it important to understand the difference between the delete and delete[] operators? Or can I just assume that whenever I allocate an array with ptr = new x[] I must also deallocate it with delete[] ptr?

推荐答案

实际上,指针指向的指针数组仍然是整数数据类型或数字数组,用于保存内存地址.两者都应使用delete[].

In reality, an array of pointers pointed to by a pointer is still an array of integral data types or numbers to hold the memory addresses. You should use delete[] for both.

此外,是的,new[]表示delete[].

创建数组数组时,实际上是在创建数字数组,而该数组恰好容纳另一个数字数组的内存地址.无论如何,它们都是数字数组,因此请用delete[]删除它们.

When you create an array of arrays, you're actually creating an array of numbers that happen to hold the memory address for another array of numbers. Regardless, they're both arrays of numbers, so delete both with delete[].

http://coliru.stacked-crooked.com/a/8a625b672b66f6ce

#include <iostream>

int main() {

    //Hey, pointers have a finite size, no matter the indirection level!
    std::cout << "sizeof(int*): " << sizeof(int*) << std::endl;
    std::cout << "sizeof(int**): " << sizeof(int**) << std::endl;
    std::cout << "sizeof(int***): " << sizeof(int***) << std::endl;

    //Create an array of pointers that points to more arrays
    int** matrix = new int*[5];
    for (int i = 0; i < 5; ++i) {
        matrix[i] = new int[5];
        for (int j = 0; j < 5; ++j) {
            matrix[i][j] = i*5 + j;
        }
    }

    //Print out the matrix to verify we have created the matrix
    for (int j = 0; j < 5; ++j) {
        for (int i = 0; i < 5; ++i) {
            std::cout << matrix[j][i] << std::endl;
        }
    }

    //Free each sub-array
    for(int i = 0; i < 5; ++i) {
        delete[] matrix[i];   
    }
    //Free the array of pointers
    delete[] matrix;

    return 0;
}

这篇关于删除动态分配的2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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