简体   繁体   English

如何在C中释放二维数组?

[英]How to free 2d array in C?

I have the following code:我有以下代码:

int **ptr = (int **)malloc(sizeof(int*)*N); 
for(int i=0;i<N;i++) 
     ptr[i]=(int*)malloc(sizeof(int)*N));

How can I free ptr using free ?如何使用free释放ptr Should I loop over ptr and free ptr[i] or should I just do我应该遍历ptr和 free ptr[i]还是应该这样做

free(ptr) 

and ptr will be freed?ptr会被释放吗?

You will have to loop over ptr[i] , freeing each int* that you traverse, as you first suggest.正如您首先建议的那样,您将不得不循环ptr[i] ,释放您遍历的每个int* For example:例如:

for (int i = 0; i < N; i++)
{
    int* currentIntPtr = ptr[i];
    free(currentIntPtr);
}

Just the opposite of allocation:与分配正好相反:

for(int i = 0; i < N; i++)
    free(ptr[i]);
free(ptr);

Yes, you must loop over ptr and free each ptr[i] .是的,您必须遍历ptr并释放每个ptr[i] To avoid memory leaks, the general rule is this: for each malloc() , there must be exactly one corresponding free() .为了避免内存泄漏,一般规则是:对于每个malloc() ,必须正好有一个对应的free()

Simple简单的

while (N) free(ptr[--N]);
free(ptr);

Handsome英俊的

#define FALSE 0
#define TRUE 1
typedef int BOOL;

void freev(void **ptr, int len, BOOL free_seg) {
    if (len < 0) while (*ptr) {free(*ptr); *ptr++ = NULL;}
    else while (len) {free(ptr[len]); ptr[len--] = NULL;}
    if (free_seg) free(ptr);
}

freev(ptr, N, TRUE); /* if known length */
freev(ptr, -1, TRUE); /* if NULL-terminated */
freev(ptr, -1, FALSE); /* to keep array */

Patrician贵族

GLib functions: GLib函数:

I find it hard to do any serious C programming without GLib.我发现没有 GLib 就很难进行任何严肃的 C 编程。 It introduces things such as dynamic strings and lays foundations for functional programming .它介绍了诸如动态字符串之类的东西,并为函数式编程奠定了基础 It should really be part of the standard C run-time library.它真的应该是标准 C 运行时库的一部分。 It would give C a breath of fresh air.它会让 C 呼吸新鲜空气。 It would make C a reasonable and competitive language again for the year 2019. But because it isn't, it will add 1 MB to your application (either in DLL size or in executable size).这将使 C在 2019 年再次成为一种合理且具有竞争力的语言但由于它不是,它将为您的应用程序增加 1 MB(无论是 DLL 大小还是可执行文件大小)。 Also the Windows distribution is maintained by sadists .此外,Windows 发行版由虐待狂维护

for(int i=0;i<N;i++) free(ptr[i]);
free(ptr);

you are not checking for malloc failure to allocate.您没有检查 malloc 分配失败。 You should always check.你应该经常检查。

 void freeMatrix(int **matrix ,int row) { for(int i=0;i<row;i++) { free(matrix[i]); } free(matrix); }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM