I'm trying to write a elaborate hello world program using MPI. The idea is that the root process sends a message to the other processes, which in turn sends a message to the root containing their process id. So I want to send several character arrays to the root process and eventually print it.
The problem is that I don't manage to collect all the messages into a variable in the root process. I only get compile errors or unwanted output. I feel like I'm making some basic error in manipulating the char arrays ... I'd be glad if you could help me out!
The code so far:
// Hello world using MPI
#include <stdio.h>
#include <math.h>
#include <mpi.h>
#include <string.h>
int main(int argc, char **argv){
// Define useful global constants
int my_id, root_process, num_procs, rc;
MPI_Status status;
char[] final_message; // <---- How should I define final message? Can I do this in another way?
// Let master process be process 0
root_process = 0;
// Now, replicate this process to create parallel processes:
rc = MPI_Init(&argc, &argv);
// Find out MY process ID and how many processes were started:
rc = MPI_Comm_rank(MPI_COMM_WORLD, &my_id);
rc = MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
// Broadcast master's message to slaves
char message1[20];
strcpy(message1, "Hello, World!");
rc = MPI_Bcast(&message1, 14, MPI_CHAR, root_process, MPI_COMM_WORLD);
// TEST: Each slave now displays message1 along with which process it is.
//printf("I'm process %i, the message is: %.13s \n",my_id,message1);
// Now the master collects a return message from each slave, including the process ID.
char message2[31];
char message22[2];
strcpy(message2, "Master, I'm process number ");// %i \n",&my_id ); //28
sprintf(message22,"%d\n",my_id);
strcat(message2,message22);
rc = MPI_Gather(message2, 1, MPI_CHAR, final_message, 1, MPI_CHAR, root_process, MPI_COMM_WORLD);
// Display the message collected by the master.
printf(final_message);
// Close down this process
rc = MPI_Finalize();
}