分享

函数参数的传递

 thunder123 2006-12-19
一个函数如果不是传递指针,那么在实际调用过程中会生成一个临时变量替代这两个传入的参数:  
   
  #include   <stdio.h>  
   
  void   add(int   a,   int   b)  
  {  
          printf("the   address   of   a   and   b   is:   %x   %x\n",&a,&b);  
  }  
   
  int   main()  
  {  
          int   a=100,   b=1;  
          printf("the   address   of   a   and   b   is:   %x   %x\n",&a,&b);  
          add(a,b);  
  }  
   
  ==================================================================  
  the   address   of   a   and   b   is:   22ff74   22ff70  
  the   address   of   a   and   b   is:   22ff50   22ff54  
   
  可以看到实际的参数已经被替代了。  
  那么如果传递指针的情况下又是什么样的呢?  
   
  #include   <stdio.h>  
   
  void   add(int   *a,   int   *b)  
  {  
          printf("the   content   of   a   and   b   is:   %x   %x\n",a,b);  
          printf("the   address   of   a   and   b   is:   %x   %x\n",&a,&b);  
  }  
   
  int   main()  
  {  
          int   x=100,   y=1;  
          int   *a=&x,   *b=&y;  
          printf("the   content   of   a   and   b   is:   %x   %x\n",a,b);  
          printf("the   address   of   a   and   b   is:   %x   %x\n",&a,&b);  
          add(a,b);  
  }  
   
  ==============================================================  
  the   content   of   a   and   b   is:   22ff74   22ff70  
  the   address   of   a   and   b   is:   22ff6c   22ff68  
  the   content   of   a   and   b   is:   22ff74   22ff70  
  the   address   of   a   and   b   is:   22ff40   22ff44  
   
  可以看到实际传递的指针也被两个临时的指针替代了,但是指针所指的地址没有改变。  
  所以我们在函数内对指针所指向的地址做的修改不会对实际的传入的指针所指地址造成修改,但是如果对所指内容做修改则会修改相应的实际数据。  
   
  在C++中又看到这样的话:  
  如果参数是指针,且仅作输入用,则应在类型前加const,以防止该指针在函数体内被意外修改。  
  例如:  
  void   StringCopy(char   *strDestination,const   char   *strSource);  
   
  在我们加了const之后则没有办法对所指内容做修改,否则会出现编译错误,但是我们还是可以改变指针指向地址,这已经无所谓了,实际的指向地址是不会改变的。  
   
  认识到所有的传入参数都会在编译器中为它分配一个临时copy  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多