gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:40:28 25 4
gpt4 key购买 nike

当我尝试使用 int(& a)[5] 通过引用传递数组时遇到错误。 但是当我想实现它时,我们应该传递一个我初始化为的引用 int & refer=*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);

关于c++ - 如何在我的实际参数中通过引用传递数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26153321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com