I am trying to pass a dynamic 2d array with bcast to all ranks.
I have the following code.
#include <stdlib.h>
#include <mpi.h>
int main(int argc, char **argv)
{
float **array;
int rank,size,i,j;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
if(rank==0)
{
array = (float **)malloc(10*sizeof(float));
for(i=0;i<10;i++)
array[i] = (float *)malloc(10*sizeof(float));
for(i=0;i<10;i++)
for(j=0;j<10;j++)
array[i][j]=i+j;
}
MPI_Bcast(array,10*10,MPI_FLOAT,0,MPI_COMM_WORLD);
MPI_Finalize();
}
For some reason i cant understand i get segmentation fault.
Anyone that knows what is the problem?
The
arrayshould be 100 rather than 10, since you assign 10 floats per each row. JackN’s answer has the code to do this.However, on any process other than rank 0, the pointer to array will be
null.You need to initialise array on all processes, then fill the array on the root.
You can just move the malloc code out of the
if (rank ==0)block and it should work how you expect.