qqqqkkkk001 2022-02-08 11:18 采纳率: 57.1%
浏览 26
已结题

C++中,数组利用值传递和地址传递有什么区别?我试了一下发现都能改变里面的值?

数组地址传递和值传递区别在哪里?都能修改的话;是不是随便自己选择?
#include<iostream>
using namespace std;


struct hero {

    string name;
};

void test01(hero *a) { //地址传递

    a->name = "王五";
    cout << "test01\t函数中:" << a->name << endl;
}

void test02(hero b[]) {//值传递

    b[0].name = "阿花";
    cout << "test02\t函数中:" << b[0].name << endl;
}
int main(){

    hero a[] = {"张三"};
    test01(&a[0]);
    cout << "test01\tmain函数中" << a[0].name << endl;

    hero b[] = { "李四" };
    test02(b);
    cout << "test02\tmain函数中" << b[0].name << endl;

    system("pause");
    return 0;
}

  • 写回答

1条回答 默认 最新

  • LYSnowy 2022-02-08 11:24
    关注

    b本身就是一个地址,即使函数中是按照值传递,但是这个值就是个地址,效果是一样的

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 2月16日
  • 已采纳回答 2月8日
  • 创建了问题 2月8日