C語言為四維陣列申請動態記憶體空間的方法(二)
阿新 • • 發佈:2019-01-03
嘗試了用堆疊的方式為四維陣列申請動態記憶體空間,並將申請記憶體的操作封裝成了子函式,方便在主程式中使用。希望對大家有用。程式碼如下:
#include <stdio.h>
#include <stdlib.h>
float**** alloc4float(int n1,int n2,int n3,int n4)
{
int i,j,k;
float**** result = NULL;
if((n1 > 0) && (n2 > 0) && (n3 > 0) && (n4 > 0 ) )
{
float*** p3 = NULL;
float** p2 = NULL;
float* p1 = NULL;
result = (float****)malloc(n1 * sizeof(float***));
p3 = (float***)malloc(n1*n2* sizeof(float**));
p2 = (float**)malloc(n1*n2*n3* sizeof(float*));
p1 = (float*)malloc(n1*n2*n3*n4* sizeof (float));
if((result != NULL) && (p1 != NULL) && (p2 != NULL)&& (p3 != NULL))
{
for(i = 0;i < n1;i++)
{
result[i] = p3 + i * n2;
for (j = 0;j < n2;j++)
{
result[i][j] = p2 + j * n3;
for (k = 0;k < n3;k++)
{
result[i][j][k] = p1 + k * n4;
}
}
p1 = p1 + n2*n3*n4;
}
}else
{
free(result);
free(p1);
free(p2);
free(p3);
result = NULL;
p1 = NULL;
p2 = NULL;
p3 = NULL;
}
}
return result;
}
void free4float(float**** p4)
{
int i,j,k;
i=j=k=0;
do{
do{
do{
free(p4[i][j][k]);
k=k+1;
}while (p4[i][j][k]!=NULL);
free(p4[i][j]);
j=j+1;
}while (p4[i][j]!=NULL);
free(p4[i]);
i=i+1;
} while (p4[i]!=NULL);
free(p4);
p4 = NULL;
}
int main()
{
int i,j,k,l;
float value=1;
int nx,ny,nz,nt;
float ****dat;
nx=ny=nz=nt=10;
dat = alloc4float(nt,nz,ny,nx);
for (i = 0; i < nx; i++)
{
for (j = 0; j < ny; j++)
{
for (k = 0; k < nz; k++)
{
for (l = 0; l < nt; l++)
{
dat[i][j][k][l] = value++;
printf("dat[%d][%d][%d][%d]=%f\n",i,j,k,l,dat[i][j][k][l]);
}
}
}
}
if(dat != NULL)
free4float(dat);
printf("End!\n");
return 0;
}
如有問題,歡迎留言~~