Omkant
Omkant

Reputation: 9204

reference to an array in c++

Question is make an array of 10 integers that's fine

int array[10];

Now question is

how to make a reference to an array which I have declared above ?

I tried this

int &ra = a;

But it's giving me error... Please provide me details about this error and how to make reference of an array.

Upvotes: 3

Views: 10689

Answers (4)

Tony Delroy
Tony Delroy

Reputation: 106086

int (&ra)[10] = a;

Alternatively, 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 ints - they occupy different amounts of memory. What you've asked for with the reference's type could be satisfied by a particular integer, 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";
}

Upvotes: 13

mada
mada

Reputation: 1975

You can typedef the array type (the type should not be incomplete) as follow:

#define LEN 10
typedef int (array)[LEN]; 

int main(void)
{
    array arr = {1, 2, 3, 4, 5};    //define int arr[10] = {1, 2, 3, 4, 5};
    array arr2;                     //declare int arr[10];
    array *arrptr = &arr;           // pointer to array: int (*arrptr)[10] = &arr;
    array &&arrvef;                 // declare rvalue reference to array of 10 ints
    array &ref = arr;               // define reference to arr: int (&ref)[10] = arr;
}

Upvotes: 1

Maksim Skurydzin
Maksim Skurydzin

Reputation: 10541

The reference to array will have type int (&a)[10].

int array[10];
int (&a)[10] = array;

Sometimes it might be useful to simplify things a little bit using typedef

typedef int (&ArrayRef)[10];
...
ArrayRef a = array;

Upvotes: 3

juanchopanza
juanchopanza

Reputation: 227390

This is a reference to an array of of ints of size 10:

int (&ra)[10];

so

int (&ra)[10] = a;

Upvotes: 1

Related Questions