当前位置:   article > 正文

C++函数参数传递的两种方式:值传递和引用传递(包括整型变量和字符串变量)_vector 传引用还是传值

vector 传引用还是传值

C语言函数参数传递的两种方式:值传递和引用传递

1 值传递

值传递包括实实在在的值传递和指针传递,指针传递参数本质上是值传递的方式,它所传递的是一个地址值,传递的都是实参的一个拷贝。

1.1 实实在在的值传递

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. void function(int num){
  5. //改变num的值
  6. num = 100;
  7. }
  8. int main()
  9. {
  10. int number;
  11. number = 1;
  12. function(number);
  13. cout << number << endl;
  14. return 0;
  15. }

这样的值传递只能把一个函数中的值传递给另一个函数,当该值在被调函数中发生改变时,在原来的函数中并不会发生改变。因为被调函数的型参只有函数被调用的时候才会临时分配单元,一旦调用结束,占用的内存便会释放,所以调用的函数中存储number的地址跟被调函数中number的地址不一样。

如果想让number通过被调函数改变该怎么做?第一种是使用指针形式的值传递,第二种是使用引用传递

1.2 指针传递

指针传递是通过地址间接的改变了实参的值。

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. void function(int* num){
  5. //通过改变num对应地址的值来实现值的改变:
  6. //形参num是一个指针,传递过来的是一个地址值,解引用即可访问到这个地址值映射的值
  7. *num = 100;
  8. }
  9. int main()
  10. {
  11. int number;
  12. number = 1;
  13. function(&number);
  14. cout << number << endl;
  15. return 0;
  16. }

2 引用传递

对引用的操作等于是对其指定的对象进行操作,当将实参传递给形参时,形参就指向了实参(形参与实参同义,是实参的一个别名)。

  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. void function(int& num){
  5. //通过引用改变num的值
  6. num = 100;
  7. }
  8. int main()
  9. {
  10. int number;
  11. number = 1;
  12. function(number);
  13. cout << number << endl;
  14. system("pause");
  15. return 0;
  16. }

3 字符串变量的函数传递与指针传递

重点: 要想用指针传递,通过函数改变主函数中字符串指针变量的值,必须使用char**的二级指针。

3.1 错误示范

先举个例子

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. void func(char* dst)
  5. {
  6. char* buf = (char*)malloc(20);
  7. memset(buf, 0, 20);
  8. strcpy(buf, "hello world!");
  9. dst = buf;
  10. puts(dst);
  11. }
  12. int main()
  13. {
  14. char* s = "123456";
  15. func(s);
  16. puts(s);
  17. return 0;
  18. }
  19. /*
  20. 本来想通过func函数改变s的值,结果并没有改变,还是输出123456
  21. */

因为以前值传递和指针传递时用的例子是整型变量,指针传递时用一级指针就可以通过函数改变主函数中的变量的值。

换成字符串变量,咋一看也是一级指针。

但是你要明白: 字符串指针的定义是什么? char* s; char* 本来就仅仅是一个字符串指针变量的类型! s存的是一个字符串的首地址值,所以你要通过函数改变字符串指针变量的值,就得用char**二级指针!

3.2 正确姿势

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. void func(char **dst) {
  5. char *buf = (char *) malloc(20);
  6. memset(buf, 0, 20);
  7. strcpy(buf, "hello world!");
  8. *dst = buf;
  9. //puts(dst);
  10. }
  11. int main() {
  12. char *s = "123456";
  13. func(&s);
  14. puts(s);
  15. return 0;
  16. }

参考

  1. https://blog.csdn.net/qq_28584889/article/details/83307592

  1. https://blog.csdn.net/qq_28584889/article/details/93789577

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/机器思考机器/article/detail/63101
推荐阅读
相关标签
  

闽ICP备14008679号