码迷,mamicode.com
首页 > 编程语言 > 详细

c++ error: creating array of references( declaration of 'a' as array)

时间:2020-03-31 12:45:15      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:eating   func   creat   clu   引用   地址   参数   通过   error   

错误程序:

#include <iostream>
using namespace std;
void func(int& a[], int n)
{
    for(int i = 0; i < n; i++)
        a[i]++;
}
int main()
{
    int a[3] = {1, 2, 3};
    func(a, 3);
    cout << a[0] << ‘ ‘ << a[1] << ‘ ‘ << a[2] << endl;
    return 0;
}

初衷:通过建立引用型形参使得func能够修改数组a的元素的值。
错因:引用型形参实际上是取实参的地址,从而获得修改实参的能力。而这里给函数传递的是数组a的首地址,地址是无法再取地址的。实际上,把a的首地址传给函数后,函数已经获得修改数组a元素的能力。

解决方法:把函数func的参数列表中的“int& a[]”改为“int a[]”即可。

正确程序:

#include <iostream>
using namespace std;
void func(int a[], int n)
{
    for(int i = 0; i < n; i++)
        a[i]++;
}
int main()
{
    int a[3] = {1, 2, 3};
    func(a, 3);
    cout << a[0] << ‘ ‘ << a[1] << ‘ ‘ << a[2] << endl;
    return 0;
}

c++ error: creating array of references( declaration of 'a' as array)

标签:eating   func   creat   clu   引用   地址   参数   通过   error   

原文地址:https://www.cnblogs.com/islch/p/12603974.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!