如何在我的实际参数中通过引用传递数组

How to pass array by reference in my actual parameters

本文关键字:引用 数组 参数 我的      更新时间:2023-10-16

当我试图使用int(&a)[5]通过引用传递数组时,遇到了一个错误。但当我想实现它时,我们应该传递一个引用,我将其初始化为int&参考=*a;以下是我的代码,以及向调用函数传递引用和指针的两种方法。如何解释我不能简单地将引用传递给它?

 #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& refer=*a;

这不是对数组的引用,而是对数组的第一个元素的引用。尝试:

int (&refer)[5] = a;
add(refer,len);