问题描述
我分配在这样一个非方阵,但我不知道如果我正确地使用释放
I allocate a non-square matrix in this way, but I'm not sure if I'm using the deallocation correctly
float **matrix_alloc(int m /* rows */, int n /* columns */)
{
int i;
float **arr = malloc(m*sizeof(*arr));
for(i=0; i<m; i++)
{
arr[i]=malloc(n*sizeof(**arr));
}
return arr;
}
我试图释放内存双向
I have tried two way to free the memory
-Attempt A 循环行
void free_mem_mat(int m, float **array) {
int i;
for (i = 0; i < m; i++) {
free(array[i]);
}
free(array);
}
- 尝试乙循环的列
void free_mem_mat(int n, float **array) {
int i;
for (i = 0; i < n; i++) {
free(array[i]);
}
free(array);
}
我应该怎么用自由?顺便:一种对行或方式 乙? (我知道书面方法是我重写这是最明显的可能是相同的)
what should I use to free? the way A on the rows or the way B? (I know as written the method is the same I have rewritten this to be most clear possible)
推荐答案
您需要有一个免费()
每个的malloc()
。有 M + 1
来电的malloc()
;你最好 M + 1
来电免费()
了。
You need one free()
for each malloc()
. There were m+1
calls to malloc()
; you'd better make m+1
calls to free()
too.
由于为出发点,选项A是正确的解决方案。然而,这也是公平地注意到这两个功能(选项A和选项B)是完全等同,只要你传递给分配函数作为在 M
尺寸在释放函数的大小参数。在选项B中的评论是一种误导;你不遍历列。
Given that as the starting point, option A is the correct solution. However, it is also fair to note that the two functions (option A and option B) are strictly equivalent as long as you pass the m
dimension given to the allocation function as the size argument of the deallocation function. The comment in option B is misleading; you're not looping over columns.
假设:
enum { MAT_ROWS = 20, MAT_COLS = 30 };
float **matrix = matrix_alloc(MAT_ROWS, MAT_COLS);
正确调用 free_mem_mat()
是:
free_mem_mat(MAT_ROWS, matrix);
这篇关于正确的方式免费M * n矩阵二维分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!