0

I am getting a compile error setting a 2D array class member in the constuctor:

#include <queue>
using namespace std;

#define N 11

struct Elem {
    Elem(uint32_t row, uint32_t col)
        : row_(row), col_(col)
    { }

    uint32_t row_, col_;
};

class Mycomp {
    public:
        Mycomp(int arr[][N])
        {
            arr_ = arr;
        }

        bool operator() (const Elem &lhs, const Elem &rhs)
        {
            return arr_[lhs.row_][lhs.col_] > arr_[rhs.row_][rhs.col_];
        }

        int arr_[][N];
};

int *mergeKArrays(int arr[][N], int k)
{
    Mycomp mycomp(arr);
    priority_queue<Elem, vector<Elem>, Mycomp> pq(mycomp);

    for (uint32_t i = 0; i < k; ++i) {
        pq.push(Elem(i, 0));
    }

    return (int *) arr;
}

int main() { }

I am getting the following error:

./mergek.cc: In constructor ‘Mycomp::Mycomp(int (*)[11])’:
./mergek.cc:23:22: error: incompatible types in assignment of ‘int (*)[11]’ to ‘int [0][11]’
             arr_ = arr;
                  ^

I have tried different variations, e.g. "&arr_[0] = arr;" did not work.

Thank you, Ahmed.

Ahmed A
  • 3,362
  • 7
  • 39
  • 57
  • 2
    Either flatten the array or use a `std::array`/`std::vector`. Otherwise you're just in for headaches. – NathanOliver Oct 12 '17 at 18:48
  • I am stuck with the prototype of function - mergeKArrays(). I could create a new 2D std::vector to represent the data pass in function as a 2D array, just to get around the compilation issue. However, trying first to see if I get the syntax right. – Ahmed A Oct 12 '17 at 18:54
  • zero-size arrays, `int arr_[][N];`, are not allowed in C++. – user4581301 Oct 12 '17 at 19:06

1 Answers1

0

Try to avoid using C style arrays and start using C++ containers like std::vectors, std::array, std::maps, etc.

In your code you tried to directly assign a array, which is not according to the rules and hence error would be lvalue must be modifiable value.

enter image description here

This problem can be rectified by visiting error : expression must be a modifiable lvalue