This works very well...
int a[5] = {1,2,3,4,5}, int *p = a;
int *& ref = p;
But why doesn't this work?
int a[5] = {1,2,3,4,5};
int*& ref = a;
Both a
and p
are pointers and have the same value (address of a[0]
).
When I make reference to an array using a pointer (p
), it works very well.
But when I make reference to that array a[]
directly, it doesn't work... Why?
a
is not a pointer, it is an array. It has the type int[5]
. What it can do is decay to a pointer int*
, which is what happens in the first case. So, taking a reference to p
is ok.
Now for the second case. Remember that a
is not a pointer. So, there is an implicit conversion happening from int[5]
to int*
. The result of that conversion is a prvalue. But you can't bind a non-const lvalue reference (which is what ref
is) to an rvalue! So the code fails to compile.
Here's an analogy:
double a = 1.4;
int& b = a; // implicit conversion from 'double' to `int` results in prvalue
// and you can't bind non-const lvalue refs to rvalues.
Adding on to what has already been answered, you can get a reference to an array like
int a[5];
int (&ref)[5] = a;
Live
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With