1

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?

klm123
  • 12,105
  • 14
  • 57
  • 95

2 Answers2

3

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);}    
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
0

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) {};
};
klm123
  • 12,105
  • 14
  • 57
  • 95
  • Why would you have a public pointer `a` pointing to an array outside the class? This class is not created with proper object-oriented design. Always strive to use OO when programming in C++. – Lundin Jan 28 '14 at 11:09
  • @Lundin, ok. I fix this. But this was small example... i didn't care here about nothing except the error. – klm123 Jan 28 '14 at 11:11
  • Yeah well, the OO issue isn't just the private encapsulation, but also that your class isn't autonomous. There is a dependency between your class and the caller, where the class must know and/or demand things of the outside world to function as intended. There may be cases where this is a reasonable approach, but in most cases such designs are questionable. – Lundin Jan 28 '14 at 11:24