# Thread: help! 3 dimensional array

1. ## help! 3 dimensional array

can you help me with my assignment..
a complete program to store the following value in a 3-dimensional array
and display the outputs of the data in the array
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16

2 4 6 8
4 8 12 16
6 12 18 24
8 16 24 32

3 6 9 12
6 12 18 24
9 18 27 36
12 24 36 48

2. Code:
```int three_dee[3][4][4] = {
{ /* First block */
{ 1, 2, 3, 4 }, /* First row */
},
};```
Extend to suit.

3. The following code does what you want...If you get in any trouble let me know.
Hope i helped.

Code:
```#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//Functions.

int ***Create3dArray(int D, int R, int C)
{
int i,j;
int ***ptrArray = NULL;
ptrArray = (int ***)calloc(D, sizeof(int **));
if(ptrArray)
{
for(i = 0; i < D && (ptrArray[i] = (int **)calloc(R, sizeof(int*))) != NULL; i++);
if(i == D)
{
for(i = 0; i < D; i++)
for(j = 0; j < R; j++)
ptrArray[i][j] = (int *)calloc(C, sizeof(int));
if(i == D && j == R)
return ptrArray;
else
return NULL;
}
else
return NULL;
}
else
return NULL;
}
void Print3dArray(int ***ptrArray, int D, int R, int C)
{
int i, j , k;
for(i = 0; i < D; i++)
{
for(j = 0; j < R; j++)
{
for(k = 0; k < C; k++)
{
printf("Array[%d][%d][%d] = %d\n", i,j,k, ptrArray[i][j][k]);
}
printf("\n");
}
printf("\n\n");
}
}
void InitArray(int ***Array, int D, int R, int C, int Start)
{
if(Array)
{
int i , j , k;
int CStart = Start;
int r = 1;
for(i = 0; i < D; i++)
{
for(j = 0; j < R; j++)
{
for(k = 0; k < C; k++)
{
Array[i][j][k] = CStart * r;
r += 1;
}
r = 1;
CStart += Start;
}
CStart = ++Start;
r = 1;
}

}
else
printf("Array is NULL.\n");
}

int main(int argc, char *argv[])
{
int ***Array = Create3dArray(3,4,4);
InitArray(Array, 3,4,4,1);
Print3dArray(Array, 3, 4, 4);
printf("Hit any key to continue...\n");
getch();
return 0;
}```

4. Shouldn't you free the memory allocated by calloc(...) at the end of your program ?

I think that allocating memory dynamically is a bit "overcomplex" for this situation, where the stack could have handle it pretty fine.

It could have looks like this
Code:
```#define D 3
#define R 4	// Would be nice to describe what all those constant mean by the way heh
#define C 4

int main()
{
int array[C][R][D];

//...

return 0;
}```
and you don't have to worry about freeing the memory since it's automatic this way.

5. Yes i agree, but should i did it all???
I used dynamic allocation because you can use it for any R,C,D.
If nio likes and surely understands my code, will expand it by adding the function which will free the memory. if not i can do it by myself by editing my message.

6. Originally Posted by Bokarinho
The following code does what you want...If you get in any trouble let me know.
Hope i helped.

Code:
`int ***Create3dArray(int D, int R, int C)`
-Error: Declaration syntax error

7. -Error: Declaration syntax error
Hmm...looks like you'll have to think of a solution, not copy one.