/* 07_column_type.c - send one column of a row-major matrix without copying it first.
 * MPI_Type_vector describes "ROWS blocks of 1 double, COLS doubles apart", which is
 * exactly one column. The receiver stores it as a contiguous array.
 * Build: mpicc -O2 -o 07_column_type 07_column_type.c
 * Run:   mpirun -np 2 ./07_column_type
 */
#include <stdio.h>
#include <mpi.h>

#define ROWS 4
#define COLS 6

int main(int argc, char **argv)
{
    int rank;
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    MPI_Datatype column;
    MPI_Type_vector(ROWS, 1, COLS, MPI_DOUBLE, &column);   /* count, blocklength, stride */
    MPI_Type_commit(&column);                              /* required before use */

    if (rank == 0) {
        double a[ROWS][COLS];
        for (int i = 0; i < ROWS; i++)
            for (int j = 0; j < COLS; j++)
                a[i][j] = 10 * i + j;                      /* value tells row and column */
        /* send column 2: start at a[0][2], one element of type 'column' */
        MPI_Send(&a[0][2], 1, column, 1, 0, MPI_COMM_WORLD);
    } else if (rank == 1) {
        double col[ROWS];
        MPI_Recv(col, ROWS, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        printf("rank 1 received column 2:");
        for (int i = 0; i < ROWS; i++) printf(" %.0f", col[i]);
        printf("\n");
    }

    MPI_Type_free(&column);
    MPI_Finalize();
    return 0;
}
