用指针传递数据的学习记录

用指针传递数据,变换的不是变量的地址,使指针指向另一个变量,解引之后取出值;而是传递的是参数的副本,以下代码说明

  1 #include<stdio.h>
  2 int main(int argc,int **argv)
  3
  4 { int tmp;
  5 int *p1,*p2;
  6
  7 printf("the address: p1:%p\n,the address:p2:%p\n",&p1,&p2);
  8 int var1,var2;
  9 p1=&var1;
 10 p2=&var2;
 11 *p1=5;
 12 *p2=6;
 13 printf("the value p1:%p\n,the value p2:%p\n",p1,p2);
 14 tmp=*p1;
 15 *p1=*p2;
 16 *p2=tmp;
 17 printf("the value p1:%p\n,the value p2:%p\n,the value of var1:%d\n,the value of var2:%d\n",p1,p2,*p1,*p2);                                     18
 19 printf("the address: p1:%p\n,the address:p2:%p\n",&p1,&p2);
 20     return 0;
 21
 22 }

 

结果:the address: p1:0x7fffd5ef5ca8
the address:p2:0x7fffd5ef5cb0
the value p1:0x7fffd5ef5c9c
the value p2:0x7fffd5ef5ca0
the value p1:0x7fffd5ef5c9c
the value p2:0x7fffd5ef5ca0
the value of var1:6
the value of var2:5
the address: p1:0x7fffd5ef5ca8
the address:p2:0x7fffd5ef5cb0

以下是用指针传递数据的相关函数:

  1 #include<stdio.h>
  2 void swap(int *p1,int *p2){
  3     int tmp;
  4     tmp=*p1;
  5     *p1=*p2;
  6     *p2=tmp;
  7 }
  8 int main(){
  9     int n1;
 10     int n2;
 11     printf("please the value of n1:");
 12     scanf("%d",&n1);
 13     printf("please the value of n2:");                                                                                                         14     scanf("%d",&n2);
 15     swap(&n1,&n2);
 16     printf("there is the swaped value:");
 17     printf("n1=%d,n2=%d",n1,n2);
 18     return 0;
 19 }

 

posted @ 2019-03-19 20:38  grandzero  阅读(443)  评论(0编辑  收藏  举报