Dynamic Memory Allocation to Multidimensional Array with MPI

Tim Broslav Source

I am currently working on modeling a diffusion process through a drug patch, which involves solving a PDE using numerical methods. My current issue is trying to dynamically allocate memory to a multidimensional array in C.

The array I am trying to allocate memory to is:

double marray[1000][1000][1000];

Also would it be possible to dynamically allocate memory to an array with another dimension? I am writing code on a 64 bit system, however, I am using a shell (Bitvise SSH client) to compile the code so that I may run it on a supercomputer(BlueShark?).

double marray[1000][1000][1000][1000];

I was given a hint at using MPI for this task?

Thank you for your interest and help!



answered 3 months ago metaTemp #1

There are several ways to make multidimensional arrays. I give you some examples: 1: let l, m, n, o,.. be your size in different dimensions.

double ****MyArr(int l, int m, int n, int o) {
    double ****array = new double ***[l];
    for (int i = 0; i<l; i++) {
        array[i] = new double **[m];
        for (int j = 0; j<m; j++) {
            array[i][j] = new double *[n];
            for (int k = 0; k < n; k++)
                array[i][j][k] = new double [o];

    return array;


create a 1D pointer instead

double *myArr new double [l*m*n*o];
//access to [a][b][c][d]
myArr[a*m*n*o + b*n*o + c*o + d]=0.0;

some remarks:

It seems you are dealing with a big matrix, make sure are using a contiguous array.

Make sure to use collective communication as much as possible if you need to communicate between processes.

All processes will make similar size array, most likely each process will use only a chunk of this array, the rest will occupy your memory for nothing. Make sure using the right size depending on the number of process.

comments powered by Disqus