如何释放在N+1个mallocs上分配的2D阵列?在C



我有一个练习,要求我释放一个用mallocs分配的2D数组。我已经在stack和许多网站上搜索过了,但我仍然被卡住了。

我必须完成一个函数,然后释放arg中的2D数组。并将其设为NULL。

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

我已经试过了这个,但它不起作用,还有两张照片是我的老师递给我的"帮帮我";但我也不太明白。

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

=>程序使崩溃

提前感谢您的帮助:(第一个图像第二个图像

由于您使用的是三星指针,因此在函数中需要一个额外的解引用:

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;
}

工作示例

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

最新更新