如何在我的实际参数中通过引用传递数组
How to pass array by reference in my actual parameters
当我试图使用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);
相关文章:
- 关于引用数组位置的问题
- 使用指针交换而不引用数组C++
- 对于Boost.Propertytree,有没有办法使用JSON点表示法来引用数组元素?
- 如何在递归函数中调用引用数组?
- 动态指针引用数组由三元运算符返回值,但有异常
- 为什么没有 std::string 构造函数来引用数组
- 指针/引用数组
- 错误 C2234:引用数组是非法的
- 引用数组的方法
- 通过引用数组值进行交换
- 引用数组涉及的技术问题
- 引用数组的函数调用
- 从其他类中的类引用数组
- 如何使用变量名称引用数组位置
- 在 OpenGL 中呈现三角形结构引用数组
- 如何取消引用数组元素(C++)
- c++引用数组数组(指针到指针?)
- 指向指针的指针如何能够引用数组
- C++取消引用数组
- c++中引用数组中对象的共享指针