Why use double indirection? or Why use pointers to pointers?

前端 未结 18 2251
失恋的感觉
失恋的感觉 2020-11-22 10:37

When should a double indirection be used in C? Can anyone explain with a example?

What I know is that a double indirection is a pointer to a pointer. Why would I ne

18条回答
  •  深忆病人
    2020-11-22 11:28

    Compare modifying value of variable versus modifying value of pointer:

    #include 
    #include 
    
    void changeA(int (*a))
    {
      (*a) = 10;
    }
    
    void changeP(int *(*P))
    {
      (*P) = malloc(sizeof((*P)));
    }
    
    int main(void)
    {
      int A = 0;
    
      printf("orig. A = %d\n", A);
      changeA(&A);
      printf("modi. A = %d\n", A);
    
      /*************************/
    
      int *P = NULL;
    
      printf("orig. P = %p\n", P);
      changeP(&P);
      printf("modi. P = %p\n", P);
    
      free(P);
    
      return EXIT_SUCCESS;
    }
    

    This helped me to avoid returning value of pointer when the pointer was modified by the called function (used in singly linked list).

    OLD (bad):

    int *func(int *P)
    {
      ...
      return P;
    }
    
    int main(void)
    {
      int *pointer;
      pointer = func(pointer);
      ...
    }    
    

    NEW (better):

    void func(int **pointer)
    {
      ...
    }
    
    int main(void)
    {
      int *pointer;
      func(&pointer);
      ...
    }    
    

提交回复
热议问题