在面试过程当中,被面试官问到传值和传引用的区别,以前没有关注过这个问题,今天在网上找了一篇包含代码和图片的讲解文章,浅显易懂,遂转载备忘。面试
1. 值传递 spa
1 void f( int p){ 2 printf("\n%x",&p); 3 printf("\n%x",p); 4 p=0xff; 5 } 6 void main() 7 { 8 int a=0x10; 9 printf("\n%x",&a); 10 printf("\n%x\n",a); 11 f(a); 12 printf("\n%x\n",a); 13 }
经过上例咱们能够看到,int a=0x10,存放的地址为0x12ff44,值为10,当调用f(a)时,传递给p的值为10,可是p的地址为0x12fef4,当改变p=0xff,时是改变地址为0x12fef4中的内容,并无改变0x12ff44中的内容,因此调用f(a),后a的值仍然为0x10,因此值传递没法改变变量的值。示意图以下:3d
2. 引用传递指针
1 void f( int & p){ 2 printf("\n%x",&p); 3 printf("\n%x",p); 4 p=0xff; 5 } 6 void main() 7 { 8 int a=0x10; 9 printf("\n%x",&a); 10 printf("\n%x\n",a); 11 f(a); 12 printf("\n%x\n",a); 13 }
经过上面引用传递传递案例咱们能够看到,调用f(a)时,传递给p的是a的地址,因此p和a的地址都是0X12ff44,因此p就是a,改变p固然能改变a。示意图以下:code
3. 指针传递blog
1 void f( int*p){ 2 printf("\n%x",&p); 3 printf("\n%x",p); 4 printf("\n%x\n",*p); 5 *p=0xff; 6 } 7 void main() 8 { 9 int a=0x10; 10 printf("\n%x",&a); 11 printf("\n%x\n",a); 12 f(&a); 13 printf("\n%x\n",a); 14 }
经过指针传递的案例咱们能够看到,调用f(&a)是将a的地址0x12ff44传递给p,则*p就指向了a的内容,改变*p后,a的内容天然就改变了,示意图以下:图片
4. 指针的引用传递class
1 void f( int*&p){ 2 printf("\n%x",&p); 3 printf("\n%x",p); 4 printf("\n%x\n",*p); 5 *p=0xff; 6 } 7 void main() 8 { 9 int a=0x10; 10 printf("\n%x",&a); 11 printf("\n%x\n",a); 12 int *b=&a; 13 printf("\n%x",&b); 14 printf("\n%x",b); 15 printf("\n%x\n",*b); 16 f(b); 17 printf("\n%x\n",a); 18 }
为了使用指针的引用传递咱们要新建一个指针b,而后将b的引用传递给p,其实p就是b的一个拷贝,*p=*b都指向a,因此改变*p的内容也就改变a的内容。示意图以下:变量
咱们再来看一下若是不用指针的引用传递会出现什么结果引用
1 void f( int*p){ 2 printf("\n%x",&p); 3 printf("\n%x",p); 4 printf("\n%x\n",*p); 5 *p=0xff; 6 } 7 void main() 8 { 9 int a=0x10; 10 printf("\n%x",&a); 11 printf("\n%x\n",a); 12 int *b=&a; 13 printf("\n%x",&b); 14 printf("\n%x",b); 15 printf("\n%x\n",*b); 16 f(b); 17 printf("\n%x\n",a); 18 printf("\n%x\n",b); 19 }
从结果中咱们能够看到调用f(b)时,传递给p的是b的内容,可是&b,和&p是不同的,虽然*p和*b都指向a。示意图以下: