0

Here is the problem. I have some "small" arrays, which I wan't to MPI_Gather into a big one, but I just want to allocate a big one on root (0) thread.

#include <mpi.h>
#include <iostream>

int main(int argc, char **argv) {

    int rank, numprocs;

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
    MPI_Status status;

    int N = 5;
    int x[N] = {1,2,3,4,5};

    int big_x[numprocs*N];
    MPI_Gather(x, N, MPI_INT, big_x, N, MPI_INT, 0, MPI_COMM_WORLD);

    if (rank == 0) {
        for (int i=0; i<numprocs*N; ++i)
            std::cout << big_x[i] << std::endl;
    }


    MPI_Finalize();
    return 0;
}

This is working code, but as you can see, I've allocated big_x on every thread. What in case I want to allocate it in only one thread? I'll get a scope error. Should I just use dynamic memory only?

1 Answers1

1

Yes, you should use dynamic memory.

int *big_x = NULL;
if (rank == 0) big_x = new int[numprocs*N];
...
if (rank == 0) delete [] big_x;

Size of a static array should be constant. So int big_x[numprocs*N] is an error because it allocates on the function start, before numprocs initialization.

Also

int N = 5;
int x[N] = {1,2,3,4,5};

is an error because N is not constant. Use const int N = 5 or #define N 5 instead.

petrmikheev
  • 342
  • 1
  • 6
  • Hello, petrmikheev, thanks for the answer, it's pretty clear. And I know that the dimension of an array should be known at pre-compiler stage, but I've just written an example, and, what is curious, this thing work. Why it can be so? (I am talking about unknown on a pre-compiler stage dimensions) – Valentin Grigorev Sep 17 '16 at 10:58
  • It is a feature of C99 and (if I am not mistaken) C++11. `gcc`/`g++` supports it by default, but other compilers may not. See http://stackoverflow.com/questions/26441916/dynamic-array-allocation-on-stack-in-c – petrmikheev Sep 17 '16 at 12:34
  • I have tried to check it. Variable length arrays are included neither in C++11, nor C++14, nor C++17. But `g++` supports it. Another link: http://stackoverflow.com/questions/1887097/variable-length-arrays-in-c#1887178 – petrmikheev Sep 17 '16 at 12:53