# Thread: multidimensional array function - simple question

1. ## multidimensional array function - simple question

Hi, I'm not an expert programmer and I'm having trouble with a function I am trying to create. I have the following code for a multidimensional array.

Code:
``` int memory_4D(){
double**** array_4D;
int i, j, k;

array_4D = (double****)malloc(NZ*sizeof(double***));
for(k=0; k<NZ; k++) {
array_4D[k] = (double***)malloc(NY*sizeof(double**));
}
for(k=0; k<NZ; k++) {
for(j=0; j<NY; j++) {
array_4D[k][j] = (double**)malloc(NX*sizeof(double*));
}
}
for(k=0; k<NZ; k++) {
for(j=0; j<NY; j++) {
for(i=0; i<NX; i++) {
array_4D[k][j][i] = (double*)malloc(N*sizeof(double));
}
}
}
return 0;
}```
I am trying to create the function memory_4D that I can call to allocate memory to all of my 4D arrays. For eaxmple, I have the arrays double**** f, double**** g, and double h**** that I want to allocate memory for. I currently have the above code typed three different times with f, g, and h replacing array_4D. I know I can create the function memory_4D that I call and assign f, g, and h with the appropriate memeory. I have tried several ways of initializing and calling memory _4D and none seem to work. I'm sure this is an easy questions. Does anyone have a suggestion?

2. As this is C++ and not C I would strongly recommend using new vs malloc:

Code:
```double**** memory_4D(int NZ, int NY, int NX, int N)
{
double**** temp;

temp = new double***[NZ];
for( int i = 0; i < NZ; ++i )
{
temp[i] = new double**[NY];
for( int j = 0; j < NY; ++j )
{
temp[i][j] = new double*[NX];
for( int k = 0; k < NX; ++k )
{
temp[i][j][k] = new double[N];
}
}
}

return temp;
}

int main()
{
double**** array_4D;

array_4D = memory_4D(2,2,2,2);  // Create a 2x2x2x2 array for example

// remember to also delete the memory allocated by new when you're done with it

...

return 0;
}```
You should also add in some checks to make sure the memory allocations are successfull.[/edit]

3. If it is C++, vectors should be used anyway. Otherwise, maybe it should be moved to the C forum.

4. As this is C++ and not C as stated, I think this also applies:
Why shouldn't my Matrix class's interface look like an array-of-array?
since arrays are evil

5. If it's C you're after, this may be of interest.

6. >You should also add in some checks to make sure the memory allocations are successfull.
Won't the runtime throw an exception if new is unsuccessful?

7. Thanks for the advice. sorry about the post. I'm new to this. The advice helped and things are working now. Once again thank you.