0

In C++, the following code will compile:

int a[5];
int (*b)[5] = &a;

while this won't:

int a[5];
int (*b)[5] = a;

When compiling the second one, g++ gives me an error, saying "cannot convert 'int*' to 'int (*)[5]' in initialization".

However, I thought that a and &a are just the same because

std::cout << a << std::endl;

and

std::cout << &a << std::endl;

produce the same result.

Apparently, there is a difference between a, which is the name of the array variable, and &a, which is the address of that array. But what exactly is the difference?

Leon
  • 33
  • 1
  • 8
  • 1
    That's like asking why `i` and `&i` for some `int i;` is not the same. What exactly is not clear to you? – Baum mit Augen Jun 07 '17 at 11:45
  • @BaummitAugen to be fair, `cout << i` can have different output than `cout << &i`, while `cout << a` is always same as `cout &a` (when a is an array and i is an integer). – eerorika Jun 07 '17 at 11:54
  • @user2079303 Not if `a` is `char[]`, but that's probably the only exception. (Also, note that my first comment is older than the clarifying edit.) – Baum mit Augen Jun 07 '17 at 11:56
  • @BaummitAugen Sorry for not commenting your comment before that edit. But why can't a be `char[]`? – Leon Jun 07 '17 at 12:13
  • It does not print the same output if `a` is `char[]` because of the `operator<<` overload for `char*`. https://wandbox.org/permlink/x6DadFBlvBpLViYJ (Also not commenting is completely fine, no need to clutter up the comment section. Just editing to clarify was the right thing to do.) – Baum mit Augen Jun 07 '17 at 12:20

2 Answers2

0

In C and C++ an array within an expression decays to a pointer to it's first element. So, in you seconds example, the left is initialized with a int* to the right.

The Techel
  • 918
  • 8
  • 13
0

Their values (addresses they are pointing to) are equal, but their types differ:

  • (in that context) a is (int [5] decayed to) int *.
  • &a is int (*)[5]

If you declare int x;, you could observe the same difference (in type but not in value) between, for example, &x and (char *)&x.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207