char*和char*&的区别


两者都是把地址传到函数中,都可以对传入的指针指向的值进行修改。不同点*&还能改变指针的指向。
下面一段程序测试*&还能改变针的指向

#include<iostream>

struct point{
  //int x;
  //int y;
};
 
void changeNum1(point *&num_ptr){
  num_ptr = new point;
  std::cout<<"test1 changeNum1 -> new num_ptr` address"<<num_ptr<<std::endl;
  //num_ptr->x = 4;
 
}

void changeNum2(point *num_ptr){
  num_ptr = new point;
  std::cout<<"test2 changeNum2 -> new num_ptr` address"<<num_ptr<<std::endl;
 // num_ptr->x = 4;
 }

void test1(){
  point *num_ptr=new point;
  std::cout<<"test1 -> num_ptr` address"<<num_ptr<<std::endl;
  //num_ptr->x = 10;
  changeNum1(num_ptr);
  std::cout<<"test1 ->out of changeNum1: num_ptr` address"<<num_ptr<<std::endl;
  //std::cout<<num_ptr->x<<std::endl;
}

void test2(){
  point *num_ptr=new point;
  std::cout<<"test2 -> num_ptr` address"<<num_ptr<<std::endl;
 // num_ptr->x=10;
  changeNum2(num_ptr);
  std::cout<<"test2 ->out of changeNum2: num_ptr` address"<<num_ptr<<std::endl;
  //std::cout<<num_ptr->x<<std::endl;
}

int main(int argc, char** argv){
  test1();
  std::cout<<"-----------------------------"<<std::endl;
  test2();
}

运行结果

test1 -> num_ptr` address0x1cdac20
test1 changeNum1 -> new num_ptr` address0x1cdb050
test1 ->out of changeNum1: num_ptr` address0x1cdb050
---------------------
test2 -> num_ptr` address0x1cdb070
test2 changeNum2 -> new num_ptr` address0x1cdb090
test2 ->out of changeNum2: num_ptr` address0x1cdb070

从运行结果我们可以看出在changeNum1()中对指针num_ptr的改变并不能改变函数外的num_ptr指向。但是使用 point*& 传入的,num_ptr可以改变函数外指针的指向。

参考地址

c++ char* char*&的区别


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM