Notes on char arrays
Working with Derived Datatypes in MPI and char arrays.
in C requires:
- Using the computation of displacements as in the code containing this
link.
- Encoding displacements taking into account char array buffering, as in the code below.
#include "mpi.h"
#include <stdio.h>
#include <string.h>
struct mytype {
char name[29]; /*30 or 31 or 32 . if necessary, all have padding to make it divisable by 4*/
int tests[2];
char report[31];
int final_grade[1] ;
};
int main(int argc, char *argv[])
{
struct mytype astudent;
int i, j, myrank;
MPI_Init(&argc, &argv);
MPI_Status status;
MPI_Datatype MPI_MYTYPE;
MPI_Datatype type[4] = { MPI_CHAR,MPI_INT, MPI_CHAR,MPI_INT};
int blocklen[4] = {29, 2 ,31,1};
MPI_Aint disp[4]={0,32,(32+2*sizeof(int)),(64+2*sizeof(int))};
MPI_Type_create_struct(4, blocklen, disp, type, &MPI_MYTYPE);
MPI_Type_commit(&MPI_MYTYPE);
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
if (myrank == 0) {
struct mytype bstudent; /* Just known to rank 0 */
strncpy(bstudent.name, "Joe Jones", 30);
bstudent.tests[0]=90; bstudent.tests[1]=93;
strncpy(bstudent.report, "excellent", 30);
bstudent.final_grade[0]=95;
printf("length of bstudent.name = %i\n",sizeof(bstudent.name));
printf("length of bstudent.tests = %i\n",sizeof(bstudent.tests));
printf("length of bstudent.report = %i\n",sizeof(bstudent.report));
printf("length of bstudent.final_grade = %i\n",sizeof(bstudent.final_grade));
printf("length of bstudent = %i\n\n",sizeof(bstudent));
MPI_Send(&bstudent, 1, MPI_MYTYPE, 1, 123, MPI_COMM_WORLD);
} else if (myrank == 1) {
struct mytype cstudent; /* Just known to rank 1 */
MPI_Recv(&cstudent, 1, MPI_MYTYPE, 0, 123, MPI_COMM_WORLD, &status);
printf("length of cstudent.name = %i\n",sizeof(cstudent.name));
printf("length of cstudent.tests = %i\n",sizeof(cstudent.tests));
printf("length of cstudent.report = %i\n",sizeof(cstudent.report));
printf("length of cstudent.final_grade = %i\n",sizeof(cstudent.final_grade));
printf("length of cstudent = %i\n\n",sizeof(cstudent ));
printf("Name: %s \n",cstudent.name);
printf("Test Grades: %i %i\n",cstudent.tests[0],cstudent.tests[1]);
printf("Performance: %s \n",cstudent.report);
printf("Grade on Final: %i \n",cstudent.final_grade[0]);
}
MPI_Finalize();
return 0;
}
A Run
length of bstudent.name = 29
length of bstudent.tests = 8
length of bstudent.report = 31
length of bstudent.final_grade = 4
length of bstudent = 76
length of cstudent.name = 29
length of cstudent.tests = 8
length of cstudent.report = 31
length of cstudent.final_grade = 4
length of cstudent = 76
Name: Joe Jones
Test Grades: 90 93
Performance: excellent
Grade on Final: 95