Hi there,
I am trying to compile the code shown below but an error appears while compiling. I have defined three functions in this code. The first function, * Array3D(), is used to allocate and initialize a three dimensional array (array3d) with zeros. The second function, DisplayArray3D(), is used to display on the screen the array3d already created. The third function, FreeArray3D(), is used to free array3d up from the memory. I think rest of the code is self-explanatory.
Any help/comment will be greatly appreciated. Thank you vey much.
Code:
typedef struct array3D_type {
double_t *** array;
int64_t size[3];
} array3D_t;
array3D_t * Array3D(int64_t sizeDim1, int64_t sizeDim2, int64_t sizeDim3);
void DisplayArray3D(array3D_t array3D);
void FreeArray3D(array3D_t * array3D);
array3D_t * Array3D(int64_t sizeDim1, int64_t sizeDim2, int64_t sizeDim3)
{
if (sizeDim1<=0)
{
fprintf(stderr, "Array3D::Error: sizeDim1 must be positive and non-zero.\n");
exit(EXIT_FAILURE);
}
if (sizeDim2<=0)
{
fprintf(stderr, "Array3D::Error: sizeDim2 must be positive and non-zero.\n");
exit(EXIT_FAILURE);
}
if (sizeDim3<=0)
{
fprintf(stderr, "Array3D::Error: sizeDim3 must be positive and non-zero.\n");
exit(EXIT_FAILURE);
}
array3D_t * array3D;
array3D->size[0]=sizeDim1;
array3D->size[1]=sizeDim2;
array3D->size[2]=sizeDim3;
array3D->array=malloc(sizeDim1*sizeof(double_t **));
if (array3D->array==NULL)
{
fprintf(stderr, "Array3D::Error: Out of memory.\n");
exit(EXIT_FAILURE);
}
for (int64_t i=0; i<sizeDim1; i++)
{
array3D->array[i]=malloc(sizeDim2*sizeof(double_t *));
if (array3D->array[i]==NULL)
{
fprintf(stderr, "Array3D::Error: Out of memory.\n");
exit(EXIT_FAILURE);
}
}
for (int64_t i=0; i<sizeDim1; i++)
for (int64_t j=0; j<sizeDim2; j++)
{
array3D->array[i][j]=malloc(sizeDim3*sizeof(double_t));
if (array3D->array[i][j]==NULL)
{
fprintf(stderr, "Array3D::Error: Out of memory.\n");
exit(EXIT_FAILURE);
}
}
for (int64_t i=0; i<sizeDim1; i++)
for (int64_t j=0; j<sizeDim2; j++)
for (int64_t k=0; k<sizeDim3; k++)
array3D->array[i][j][k]=0.;
return array3D;
}
void DisplayArray3D(array3D_t array3D)
{
printf("Array3D::Size=(%lli,%lli,%lli).\n", array3D.size[0], array3D.size[1], array3D.size[2]);
for (int64_t k=0; k<array3D.size[2]; k++)
{
printf("\nArray3D(:,:,%lli)=\n", k+1);
for (int64_t i=0; i<array3D.size[0]; i++)
{
printf("R%lli:\t",i+1);
for (int64_t j=0; j<array3D.size[1]; j++)
printf("%lf\t", array3D.array[i][j][k]);
printf("\n");
}
}
}
void FreeArray3D(array3D_t * array3D)
{
for (int64_t i=0; i<array3D->size[0]; i++)
for (int64_t j=0; j<array3D->size[1]; j++)
free(array3D->array[i][j]);
for (int64_t i=0; i<array3D->size[0]; i++)
free(array3D->array[i]);
free(array3D->array);
free(array3D);
}
int main (void)
{
array3D_t * s=Array3D(5,3,4);
for (int i=0; i<s->size[0]; i++)
for (int j=0; j<s->size[1]; j++)
for (int k=0; k<s->size[2]; k++)
s->array[i][j][k]=5/3.*i-2*j+7*k;
DisplayArray3D(*s);
FreeArray3D(s);
return 0;
}
Thank you!