char*和char*&的区别

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

#include

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

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

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

运行结果

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*&的区别

你可能感兴趣的:(char*和char*&的区别)