int (&ra)[10] = a;
Alterantively, you can use a typedef to separate this into the type for "array of 10 ints" and having a reference there-to, as in:
typedef int int10[10];
int10& my_ref = a;
The problem with your int &ra = a;
is that it tells the compiler to create a reference of type int
that refers to an array of 10 ints
... they're just not the same thing. Consider that sizeof(int)
is a tenth of the size of an array of ten int
s - they occupy different amounts of memory. What you've asked for with the reference's type could be satisfied by a particular character, as in int& ra = a[0];
.
I appreciate it's a bit confusing that int* p = a;
is allowed - for compatibility with the less type-safe C, pointers can be used to access single elements or arrays, despite not preserving any information about the array size. That's one reason to prefer references - they add a little safety and functionality over pointers.
For examples of increased functionality, you can take sizeof(my_ref)
and get the number of bytes in the int
array (10 * sizeof(int)
), whereas sizeof p
would give you the size of the pointer (sizeof(int*)
) and sizeof *p == sizeof(int)
. And you can have code like this that "captures" the array dimension for use within a function:
template <int N>
void f(int (&x)[N])
{
std::cout << "I know this array has " << N << " elements\n";
}