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

前端 未结 18 2236
失恋的感觉
失恋的感觉 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:20

    One reason is you want to change the value of the pointer passed to a function as the function argument, to do this you require pointer to a pointer.

    In simple words, Use ** when you want to preserve (OR retain change in) the Memory-Allocation or Assignment even outside of a function call. (So, Pass such function with double pointer arg.)

    This may not be a very good example, but will show you the basic use:

    void allocate(int** p)
    {
      *p = (int*)malloc(sizeof(int));
    }
    
    int main()
    {
      int* p = NULL;
      allocate(&p);
      *p = 42;
      free(p);
    }
    

提交回复
热议问题