在C程序中可调用如下函数进行高维数组的动态分配与释放。
高维数组动态分配函数:
//--- for dynamic memory allocation ---
/************
* ARRAY3D * Memory allocation procedure for 3D arrays
************/
float ***Array3D(int columns, int rows, int floors)
{
float ***x;
int i, j;
if ((x = (float ***)malloc(columns * sizeof(float**))) == NULL ) {
fprintf(stderr, "mb3dat: can't allocate memory");
}
for (i = 0; i < columns; i++) {
if ((x[i] = (float **)malloc(rows * sizeof(float*))) == NULL) {
fprintf(stderr, "mb3dat: can't allocate memory");
}
for (j = 0; j < rows; j++)
if ((x[i][j] = (float *)malloc(floors * sizeof(float))) == NULL) {
fprintf(stderr, "mb3dat: can't allocate memory");
}
}
return x;
} // end Array3D()
=========================================================================================
高维数组释放函数:
//--- for dynamic memory deallocation ---
/****************
* FreeARRAY3D * Memory deallocation procedure for 3D arrays
****************/
void FreeArray3D(float ***uu,int columns, int rows, int floors)
{
int i, j;
for (i = 0; i < columns; i++)
{
for (j = 0; j < rows; j++){
free(uu[i][j]);
}
free(uu[i]);
}
free(uu);
return;
} // end FreeArray3D()
=========================================================================================
调用示例:
// 分配内存
float ***uu;
uu = Array3D(LEN, HIG, DEP);
// 释放内存
FreeArray3D(uu,LEN, HIG, DEP);