Reputation: 145
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?
Upvotes: 0
Views: 131
Reputation: 342
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.
Upvotes: 1