免费的二维数组列 [英] Free 2D array columns

查看:163
本文介绍了免费的二维数组列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串的二维数组,这个动态分配的:

I have a 2D array of strings, dynamically allocated with this:

char*** allocateArray(int line, int col)
{
    char*** dictionary;
    int i=0,j=0;
    dictionary=(char***)malloc(sizeof(char**)*line);
    for(i=0;i<line;i++)
    {
        dictionary[i] = (char**)malloc(sizeof(char*));
        for(j=0;j<col;j++)
            dictionary[i][j] = (char*)malloc(sizeof(char*));
    }
    return dictionary;
}

现在我要释放的最后一列(可以说),我该怎么办?
我使用免费(词典[I] [J]。),但到底是什么,它​​实际上免费的吗?在 [I] [J] 磁盘阵列,它指向指针细胞?
我需要释放两者。

Now I want to free the last column (lets say), what should I do ? I use free(dictionary[i][j]), but what does it actually free ? The [i][j] cell in the array, or the pointer that it points to? I need to free both.

推荐答案

请记住,你必须在你保留的内存相反的顺序释放内存。在这种情况下,它是正确的遍历Ĵ用于释放词典[I] [J] (其中指数 I 是固定的),因为那时你会释放对 *(*(词典+一)+ J)保留的空间。之后,你会遍历 I 用于释放词典[I] (从而释放了<$ C $保留的空间C> *(字典+ I ),最后,你只免费(字典)(和你释放 *字典)。

Keep in mind that you have to free memory in the reverse order you reserved the memory. In this case, it is correct to loop over j for freeing dictionary[i][j] (where the index i is fixed), because then you'd be freeing the space reserved for *(*(dictionary + i) + j). After that you would loop over i for freeing dictionary[i] (which frees the space reserved for * (dictionary + i), and finally, you would just free (dictionary) (and you are freeing * dictionary).

请注意:订单你自由的空间的确很重要,因为如果你释放的内存块,实际上是指向保留内存的另一个块,那么你就不能释放此最后一次了,所以你将有内存泄漏。这就是为什么你必须开始以释放内存在,你叫的malloc 秒。

Note: the order you free space does matter because if you free a block of memory that is actually pointing to another block of reserved memory, then you can't free this last one anymore, so you will have memory leaks. That's why you have to start to free memory in the reverse order you called mallocs.

汇总,这块code将正常工作到你(我Valgrind的测试了,而且没有内存泄漏):

Summarizing, this piece of code will work fine into yours (I tested it with Valgrind, and there is no memory leaks):

for (i = 0; i < line; i++){
    for (j = 0; j < col; j++){
        free (dictionary[i][j]);
    }
    free (dictionary[i]);
}

free (dictionary);

您可以看到如何释放一个二维数组<一个一个解释例子href=\"http://danielmbcn.word$p$pss.com/2013/07/07/some-notes-about-dynamic-memory-allocation-of-multi-dimensional-arrays/\"相对=nofollow>此处。我希望它能够对您有用:)

You can see an explained example of how to free a 2-D array here. I hope it can be useful for you :)

这篇关于免费的二维数组列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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