0

I don't have much experience with C++ or MPI currently, so I assume this will be an easy question to answer.

I want to be able to change the number of processes that can work on my array sort for experimentation purposes, but when I try to declare a partial array for my worker to work on, I receive an error stating that the array size variable, PART, needs to be constant.

Is this from how I calculated or parsed it, or from an MPI mechanic?

const int arraySize = 10000    

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

        int rank;
        int size;

        MPI_Comm_rank(MPI_COMM_WORLD, &rank);
        MPI_Comm_size(MPI_COMM_WORLD, &size);

        const int PART = floor(arraySize / size);

        auto start = std::chrono::high_resolution_clock::now(); //start timer

        //================================ WORKER PROCESSES ===============================
        if (rank != 0)
        {
            int tmpArray[PART];       //HERE IS MY PROBLEM

            MPI_Recv(&tmpArray, PART, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);    //recieve data into local initalized array
            qsort(&tmpArray[0], PART, sizeof(int), compare);                                // quick sort
            MPI_Send(&tmpArray, PART, MPI_INT, 0, 0, MPI_COMM_WORLD);                       //send sorted array back to rank 0
        }
  • You should probably look into [`std::vector`](http://en.cppreference.com/w/cpp/container/vector). Vanilla C arrays should rarely be used any more. – pingul Nov 16 '17 at 01:25

2 Answers2

1

auto tmpArray = std::make_unique<int[]>(PART);

Jesin
  • 1,009
  • 9
  • 12
  • 1
    better to use `std::make_unique(PART);` without calling `new` directly – Semyon Burov Nov 16 '17 at 01:37
  • @SemyonBurov can you explain how/why that is better? – Jesin Nov 16 '17 at 01:56
  • 1
    @Jesin Because `std::unique_ptr` and `std::shared_ptr` is all about giving up memory management to stl and dont worry about it. More here: https://stackoverflow.com/questions/22571202/differences-between-stdmake-unique-and-stdunique-ptr – Semyon Burov Nov 16 '17 at 02:18
0

If the size of an array is determined at runtime, as in your case, this would give a variable length array, which is supported in C, but not in standard C++. So in C++, the size of an array needs to be a (compile time) constant.

To overcome this, you'll have to use dynamic memory allocation. This can be achieved either through "classic C" functions malloc and free (which are rarely used in C++), through their C++-pendants new and delete (or new[] and delete[]), or - the preferred way - through the use of container objects like, for example, std::vector<int> that encapsulate this memory allocation issues for you.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58