zoukankan      html  css  js  c++  java
  • 写哪儿指哪儿——值传递

    时至今日还在纠结这类问题,实在是惭愧……

    C/C++的参数是值传递。也就是说形参(仅在该函数内部可以访问)只是实参的一份拷贝。

    通常,为了改变一个数值,我们传入指向这个数值的指针,函数体内改变这个指针的指向,从而改变对应数值。

    void swap(int *p, int *q)
    {
      int tmp = *p;
      *p = *q;
      *q = tmp;
    }
    
    
    int main () {
       int a = 1, b = 2;	
       swap(&a,&b);
       return 0;
    }
    

    这样或许更直观:

    int main () {
       int a = 1, b = 2;
       int *p,*q;
       p = &a;
       q = &b;
       printf("%d %d
    ",*p,*q); // 1 2
    
       swap(p,q);
       printf("%d %d
    ",*p,*q); // 2 1
       return 0;
    }
    
    

    改变指针的值?

    现在有个函数要改变一个指针,一开始,我写成了这样:

    void pointToRoot(int *root, int *q)
    {
      q = root;
    }
    
    int main () {
       int a = 1, b = 2;
       int *root,*q;
       root = &a;
       q = &b;
       printf("%d %d
    ",*root,*q); //1 2
    
       pointToRoot(root,q);
       printf("%d %d
    ",*root,*q); //1 2
       return 0;
    }
    
    

    虽然在函数pointToRoot里改了q的值,但是改的是形参,对main里q并没有效果。
    我们要改指针q,那么我们需要传入的参数就应该是指向指针q的指针&q,在函数pointToRoot里改变&q指向的值:

    void pointToRoot(int *root, int **q_ref)
    {
      *q_ref = root;
    }
    
    
    int main () {
       int a = 1, b = 2;
       int *root,*q;
       root = &a;
       q = &b;
       printf("%d %d
    ",*root,*q);  //1 2
    
       pointToRoot(root,&q);
       printf("%d %d
    ",*root,*q);  //1 1
    	
       *root = 3;
       printf("%d %d
    ",*root,*q);  //3 3
       return 0;
    }
    
    
  • 相关阅读:
    Codeforces Round #251 (Div. 2) A
    topcoder SRM 623 DIV2 CatAndRat
    topcoder SRM 623 DIV2 CatchTheBeatEasy
    topcoder SRM 622 DIV2 FibonacciDiv2
    topcoder SRM 622 DIV2 BoxesDiv2
    Leetcode Linked List Cycle II
    leetcode Linked List Cycle
    Leetcode Search Insert Position
    关于vim插件
    Codeforces Round #248 (Div. 2) B. Kuriyama Mirai's Stones
  • 原文地址:https://www.cnblogs.com/garcia-0/p/4661560.html
Copyright © 2011-2022 走看看