3

is it possible to broadcast array of strings defined as

char **lines;
lines = malloc(512 * sizeof(char*));

I have tried

MPI_Bcast(lines, linesCount, MPI_BYTE, 0, MPI_COMM_WORLD);

and

MPI_Bcast(lines, linesCount, MPI_CHAR, 0, MPI_COMM_WORLD);

where linesCount is number of strings in array.

How can it be achieved?

somik07
  • 39
  • 9
  • Strings may be a bit special, but they are just a array of pointers. Check out [this question](https://stackoverflow.com/questions/9507987/mpi-sending-array-of-array). There's also this [(not properly answered) duplicate](https://stackoverflow.com/questions/19744458/sending-string-array-mpi-c) – Zulan Dec 06 '17 at 21:12

1 Answers1

2

Assuming the strings that you store in the lines array may have a varying size, you can first broadcast an int array of sizes of each string and then broadcast each string separately,

/* Create an Array with length of each line 
   Broadcast it from process 0 */ 
int lin_siz[linesCount];
if (p_rank == 0)
    for (i=0; i < linesCount; i++)
        lin_siz[i] = strlen(lines[i])+1;
MPI_Bcast(&lin_siz, linesCount, MPI_INT, 0, MPI_COMM_WORLD);

/* Broadcast each line */
for (i=0; i < linesCount; i++)
    MPI_Bcast(&lines[i], lin_siz[i], MPI_CHAR, 0, MPI_COMM_WORLD);

MPI_Bcast can broadcast only elements that are contiguous in memory - in this case the int array with sizes, lin_siz and each line stored in lines. This may not be a very elegant solution and better is surely possible but it works.

It was tested with the following array

char **lines;
lines = malloc(linesCount * sizeof(char*));

if (p_rank == 0){
    for (i=0; i<linesCount-2; i++)
        lines[i] = "This is a test.";
    lines[i++] = "More testing.";
    lines[i++] = "Even more..";
}

with p_rank being a standard processor rank obtained with MPI_Comm_rank(MPI_COMM_WORLD, &p_rank). And successfully printed at the end as

/* Print */
printf("Process rank %d:\n", p_rank);
for (i=0; i < linesCount; i++)
     printf("%s\n", lines[i]);

I can post the entire test case if you have issues implementing my answer.

atru
  • 4,699
  • 2
  • 18
  • 19