1

I have a array int b[MAXN][MAXN];

When I use int a[][MAXN] = b; (I know that int (*a)[MAXN] is OK) It gives me an error.

But If I have a function void f(int a[][MAXN]) When I call f(b); It works!

Does someone can tell me why?

zakinster
  • 10,508
  • 1
  • 41
  • 52
edward_mj
  • 31
  • 4

2 Answers2

1

When declaring function parameters, T[] is treated the same as T*, i.e. it declares the parameter as a pointer. So void f(int a[][MAXN]) simply declares the parameter a to be a pointer to int arrays of size MAXN.

For other kinds of variables, it is not the same though. That is when you write int a[][MAXN] = b, this declares a as an array or arrays, not a pointer to arrays. And that's why that doesn't work (because you can't make arrays "point" to other arrays like that).

Note that this isn't specific to arrays of arrays. It's the same if you compare void f(int a[]) to int a[] = b. In the former case the parameter a would simply be an int pointer (just as if you had written int *a) and in the latter case a would be an array and you'd get an error for the same reason as above.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • 1
    Note also that OP can assign a as a reference to b, just fine: int (& a)[MAXN][MAXN] = b; It's only aggregate initialization of an array with another that is not supported. – Scott Jones May 13 '13 at 13:47
0

You cannot initialize [in declaration] any array variable with another like this:

int a[1] = {};
int b[] = a;

That's not a decaying to pointer situation. You seem to want to declare a new array, which would be a copy of the first one. When passing arrays as function parameters like you have shown, they'll decay to pointers, and you won't be creating a new array.

If, instead, you want a reference, you could do:

int a[1] = {};

int (&b)[1] = a;  // first reference
auto &c = a;      // second rerefence

If you want to make a copy, then make a copy:

int a[1] = { 42 };

int b[1];
decltype(a) c;

std::copy(std::begin(a), std::end(a), b);
std::copy(std::begin(a), std::end(a), c);
oblitum
  • 11,380
  • 6
  • 54
  • 120