c++ error: creating array of references( declaration of

错误程序:

#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;
}

原文链接: https://www.cnblogs.com/islch/p/12603974.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    c++ error: creating array of references( declaration of

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/338968

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午11:51
下一篇 2023年3月1日 下午11:52

相关推荐