【发布时间】:2015-07-09 03:15:08
【问题描述】:
如何使用使用 int ** ptr 分配内存的函数释放二维数组?
例如我使用allocArray( &ptrArray, row, column); 来分配数组。
使用此函数释放分配的内存的正确过程是什么:
void freeArray( int *** pA, int row, int column)
#include <stdio.h>
#include <stdlib.h>
void allocArray( int *** pA, int row, int column)
{
int i, j, count;
*pA = (int **) malloc(row * sizeof(int *));
for (int i =0; i<row; ++i)
{
(*pA)[i] = (int *) malloc( column * sizeof(int));
}
// Note that pA[i][j] is same as *(*(pA+i)+j)
count = 0;
for (i = 0; i < row ; i++)
for (j = 0; j < column; j++)
(*pA)[i][j] = ++count; // OR *(*(pA+i)+j) = ++count
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++) {
printf("%d ", (*pA)[i][j]);
}
printf("\n");
}
}
// How to free a two dimensional array allocated memory using int ** ptr?
void freeArray( int *** pA, int row, int column)
{
}
void test_array_allocation()
{
int i, j;
int row = 3, column = 4;
int ** ptrArray;
allocArray( &ptrArray, row, column);
printf("test_array_allocation\n");
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++) {
printf("%d ", (ptrArray)[i][j]);
}
printf("\n");
}
freeArray(&ptrArray, row, column); // free allocated memory
}
int main(int argc, const char * argv[]) {
test_array_allocation();
return 0;
}
【问题讨论】:
-
基本相同,但顺序相反:首先,释放每个
(*pA)[i],然后释放*pA。你可能想重新设计你的代码。当int ***之类的东西开始出现时,这很少是一个好兆头。 -
如果你这样做,你能告诉我你会怎么做吗?
-
最好使用函数原型:'void * allocArray(int nodeLength, int numRow, int numCol) 函数内部:void * theArray = NULL;然后分配行指针并将它们全部清除为NULL。然后,分配每一行的列。最好是单独初始化行列的初始化,而不是作为数组分配的一部分。
-
在 C 中调用 malloc()(和函数族)1) 时,不要转换返回值。 2) 始终检查 (!=NULL) 返回值以确保操作成功。
-
为行指针调用 malloc 的初始结果应该将结果分配的内存设置为 NULL。那么如果出现任何问题,释放内存将是一个简单的循环(将 NULL 传递给 free() 就可以了)
标签: c arrays memory free pointers