Initialization of 2D array data member

321 views Asked by At

I have a program like this:

class A {
  int a[2][3];
 public:
  A(int b[2][3]): a(b) {};
};

int main() {
  int b[2][3];
  A myclass(b);
  return 1;
}

The compiler says:

1.cpp: In constructor 'A::A(int (*)[3])':
1.cpp:5:22: error: incompatible types in assignment of 'int (*)[3]' to 'int [2][3]'

Why are they incompatible and how can I initialise array A::a by another array b?

2

There are 2 answers

3
klm123 On

int a[2][3] is basically a constant pointer. One can't assign to constant pointer. You can only copy the full content. If you need to copy the pointer only you need to declare a pointer instead of array:

class A {
  int (*a)[3];
 public:
  A(int b[2][3]): a(b) {};
};
0
Mike Seymour On

For historical reasons, built-in array types are rather inconvenient second-class types which can't be copied or passed to functions by value. Instead, they tend to decay to pointers; despite the syntax, your constructor argument is actually a pointer, equivalent to

A(int (*b)[3])

hence the error message complaining that a pointer can't be assigned to an array.

You could wrap the array in a class, making a more conveniently copyable type; in C++11, the standard library already provides such an array template:

typedef std::array<std::array<int,2>,3> array;
array a;
A(array const & b) : a(b) {}

If you really want to stick with a built-in array, then you'll need to copy the data by steam:

A(int b[2][3]) {std::copy(b, b+3, a);}