繁体   English   中英

如何释放分配在 N+1 malloc 上的二维数组? 在 C

[英]How to free a 2D array allocated on N+1 mallocs ? In C

我有一个练习,要求我释放一个用 malloc 分配的二维数组。 我已经在堆栈和许多网站上搜索过,但我仍然卡住了。

我必须完成一个 function 然后释放 arg 中的二维数组。 并使其成为 NULL。

void FreeMatrix(int*** ptab, int N){
   /// to complete
}

我已经尝试过了,但它不起作用,还有两张照片是我的老师交给我的“帮助我”,但我也不太明白。

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

=> 程序崩溃

提前感谢您的帮助:(第一张图片第二张图片

由于您使用的是 3 星指针,因此您需要在 function 中额外取消引用:

void FreeMatrix(int*** ptab, int N)
{
    for (size_t i=0; i<N; i++)
    {
        // *ptab is an int** type, and that makes (*ptab)[i] an
        // int* type. Presumably, you've malloced N int* types, so
        // free each of those
        free((*ptab)[i]);
    }

    // now free the initial int** allocation
    free(*ptab);
    // and set it to NULL per your requirements
    *ptab= NULL;
}

工作示例

请注意,3 星指针通常被认为是糟糕的设计

暂无
暂无

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

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