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;
}
}
int a[]to pass an array for modification in a function. In C++ you can usestd::vector<int>&and take advantage of the fact a vector knows its size.adoesn't decay to pointer, so you know the size (and may removeint len).