user2804418
user2804418

Reputation: 43

MPI Broadcasting 2d array

I was going to study parallel programming with MPI. And I've got some error

#include "mpi.h"
#include <stdio.h>
#include <stdlib.h>


int main(int argc, char** argv)
{
    int procNum, procRank;
    int m,n;
    int sumProc = 0, sumAll = 0;
    int** arr;
    MPI_Status status;

    MPI_Init ( &argc, &argv );

    MPI_Comm_size ( MPI_COMM_WORLD, &procNum ); 
    MPI_Comm_rank ( MPI_COMM_WORLD, &procRank );

    if (procRank == 0)
    {   
        printf("Type the array size \n");
        scanf("%i %i", &m, &n); 
    }
    MPI_Bcast(&m, 1, MPI_INT, 0, MPI_COMM_WORLD);
    MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);

    arr = new int*[m];
    for (int i = 0; i < m; i++)
        arr[i] = new int[n];

    if (procRank == 0)
    {
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                    arr[i][j] = rand() % 30;
                    printf("%i ", arr[i][j]);
            }
            printf("\n");
        }
    }

    MPI_Bcast(&arr[0][0], m*n, MPI_INT, 0, MPI_COMM_WORLD);

    for (int i = procRank; i < n; i += procNum)
        for (int j = 0; j < m; j++)
            sumProc += arr[j][i];

    MPI_Reduce(&sumProc,&sumAll,1,MPI_INT,MPI_SUM,0,MPI_COMM_WORLD);

    if (procRank == 0)
    {
        printf("sumAll = %i", sumAll);
    }

    delete *arr;

    MPI_Finalize();
    return 0;
}

I'm trying to pass 2d array to other processes, but when I check it out I get wrong array. Something like this:

Original array
11 17 4
10 29 4
18 18 22

Array which camed
11 17 4
26 0 0
28 0 0

What the issue is it? Maybe issue is in MPI_Bcast

P.S. I added

for (int i = 0; i < m; i++)
    MPI_Bcast(arr[i], n, MPI_INT, 0, MPI_COMM_WORLD);

instead of

MPI_Bcast(&arr[0][0], m*n, MPI_INT, 0, MPI_COMM_WORLD);

It solved my question

Upvotes: 4

Views: 5349

Answers (1)

Here

arr = new int*[m];
for (int i = 0; i < m; i++)
    arr[i] = new int[n];

you create a 2D array by first creating an array of pointers, and then creating regular int arrays for each of them. Using this method, all your arrays a[i] are each n elements in size, but are not guaranteed to be contiguous in memory.

Later, however, with

MPI_Bcast(&arr[0][0], m*n, MPI_INT, 0, MPI_COMM_WORLD);

you assume that all your arrays are contiguous in memory. Since they are not, you get different values.

Upvotes: 3

Related Questions