0

I came across an error when I tried to pass array by reference using int(& a)[5]. But when I wanna implement it ,we should pass a reference which I initialize as int & refer=*a; Following is my code ,and two ways to pass reference and pointer to the calling function . How to explain that I can't simply pass a reference into it?

 #include <iostream>

using namespace std;

void add(int (&)[5],int );
int main()
 {


int a[5]={5,4,3,2,1};
int len=sizeof(a)/sizeof(a[0]);
cout<<"len="<<len<<endl;
cout<<"a="<<a<<endl;// the name of array is actually the pointer

int& refer=*a;

add(a,len);    //which is correct,we pass a pointer to the calling function;
add(refer,len);   //which is wrong,we pass a reference to the calling function;
for(int i=0;i<len;i++){
    cout<<a[i]<<" ";
}

return 0;
}



void add(int (&a)[5],int len){
  for(int i=0;i<len;i++){
   a[i]=a[i]+10;
  }
}
4
  • 1
    If add only takes an array of size 5, why do you pass the length? You only need int a[] to pass an array for modification in a function. In C++ you can use std::vector<int>& and take advantage of the fact a vector knows its size. Commented Oct 2, 2014 at 1:53
  • Because I wanna know how many times I should loop. When I pass a[] into a calling function, a[] decays to the pointer to the first element.In that sense, I would lose my information about the size of this array,which means I should add the length of my array together. Commented Oct 2, 2014 at 2:01
  • @user3570984: With this signature, a doesn't decay to pointer, so you know the size (and may remove int len). Commented Oct 2, 2014 at 7:14
  • But the size is right there, in the function signature! Commented Oct 2, 2014 at 9:17

1 Answer 1

2
int& refer=*a;

This is not a reference to the array, but to its first element. Try:

int (&refer)[5] = a;
add(refer,len);
Sign up to request clarification or add additional context in comments.

3 Comments

As for int (&refer)[5] = a; I don't quite understand why you can assign pointer,like a,to a reference.
@user3570984: Because a is not a pointer. It's an array. The expression a decays to pointer in certain contexts, essentially where a pointer is expected. Also note that this is not assignment. It's initialization, although expressed with an = sign.
@user3570984 You can have a reference to an array (or a pointer) pretty much the same way as a reference to an integer. The line int (&refer)[5] = a; says " refer is a reference to a".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.