Sending a vector of char array using MPI_Send

  c++, char, mpi, string, vector

I am implementing a C++ project using MPI and I have a problem in sending a vector of char array from one process to another. In particular, I start with a vector of type string but, since there is no string type in MPI, I first convert it into char*. I was able to do it and I can print the values of the resulted vector on the first process but, afterwards, when I use MPI_Send and MPI_Recv, on the second process I get an error and I’m not able to retrieve the values out of the received vector.

This is a reproducible code that simulate my attempt:

#include "mpi.h"
#include <bits/stdc++.h>
using namespace std;

int main(int argc, char **argv) {
  int rank, numprocs;
  int namelen;

  MPI_Init(NULL, NULL);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  MPI_Comm_size(MPI_COMM_WORLD, &numprocs);

  std::vector<std::string > strings;
  std::vector<char* > cstrings;

  if (rank==0) {
    strings.push_back("fe");
    strings.push_back("fo");
    
    for(int i=0; i<strings.size(); i++){
      string st = strings[i];
      cstrings.push_back(&st[0]);
    }

    for(int i=0; i<cstrings.size(); i++){
      cout << cstrings.data()[i] << endl;
    }
            
    MPI_Send(&cstrings[0], cstrings.size(), MPI_CHAR, 1, 0, MPI_COMM_WORLD);
  }
  if (rank==1) {
    cstrings.resize(2);
    MPI_Recv(&cstrings[0], cstrings.size(), MPI_CHAR, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
    
    for(int i=0; i<cstrings.size(); i++){
      cout << cstrings.data()[i] << endl;
    }
  }

  MPI_Finalize();
  return 0;
}

What is the problem? How can I solve it? Thanks in advance!

Source: Windows Questions C++

LEAVE A COMMENT