I have a problem with using scatter in mpi
this is my code I have a matrix n*m when the process id is 0 I enter the n and m and put values in arr the broadcast n and m to other process and I use scatter to divide the matrix on them and I recive the value of matrix in temp arr and I don’t know if arr has a garbage value or temp don’t recive the values it shoud find the max value in the matrix
#include <mpi.h>
#include <iostream>
#include <unistd.h>
#include <string>
#include <math.h>
#include <chrono>
using namespace std;
using namespace chrono;
int main(int argc, char **argv) {
int id, np;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &id); // return the id of the process
MPI_Comm_size(MPI_COMM_WORLD, &np); // return the number of processes
int n, m;
int **arr;
int **temp;
if(id == 0) {
printf("enter n and mn");
cin >> n >> m;
arr = new int*[n];
for(int i = 0; i < n; i++) {
arr[i] = new int[m];
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
arr[i][j] = i + j;
}
}
}
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&m, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
temp = new int*[n/np];
for(int i = 0; i < n/np; i++) {
temp[i] = new int[m];
}
MPI_Barrier(MPI_COMM_WORLD);
MPI_Scatter(&arr, (n/np) * m, MPI_INT, &temp[0][0], (n/np) * m, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
printf("temp from id %d n-> %d m->%d n", id,n,m);
for(int i = 0; i < n/np; i++) {
for(int j = 0; j < m; j++) {
printf(" %d ", temp[i][j]);
}
printf("n");
}
printf("n");
MPI_Barrier(MPI_COMM_WORLD);
int mx = -1;
for(int i = 0; i < n/np; i++) {
for(int j = 0; j < m; j++) {
mx = max(mx, temp[i][j]);
}
}
int ans;
MPI_Reduce ( &mx, &ans, 1, MPI_INT, MPI_MAX, 0, MPI_COMM_WORLD );
MPI_Barrier(MPI_COMM_WORLD);
if(id == 0) {
printf("the max is %dn", ans);
}
return 0;
}