When to use Pointer-to-Pointer in C++?

后端 未结 6 1626
小鲜肉
小鲜肉 2021-02-13 20:38

I was wondering when we use Pointer to Pointer in C++ and why we need to point to a pointer? I know that when we point to a pointer it means we are saving the memory address of

6条回答
  •  隐瞒了意图╮
    2021-02-13 21:08

    When you want to change the value of variable passed to a function as the function argument, and preserve updated value outside of that function, you require pointer(single pointer) to that variable.

    void modify(int* p)
    {
      *p = 10;
    }
    
    int main()
    {
      int a = 5;
      modify(&a);
      cout << a << endl;
    }
    

    Now when you want to change the value of the pointer passed to a function as the function argument, 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 safe_free(int** p) 
    { 
      free(*p); 
      *p = 0; 
    }
    
    int main()
    {
      int* p = (int*)malloc(sizeof(int));
      cout << "p:" << p << endl;
      *p = 42;
      safe_free(p);
      cout << "p:" << p << endl;
    }
    

提交回复
热议问题