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

后端 未结 6 1629
小鲜肉
小鲜肉 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:02

    We basically need pointer to pointer when we want to change the address of the pointer it is pointing to. very good example will be the case of linked list where we send a pointer to pointer to the head node when we try to insert a value to the beginning. Snippet of code pasted below.

    int main()
    {
        /* Start with the empty list */
        struct node* head = NULL;
        
        /* Use push() to construct below list
            1->2->1->3->1  */
        push(&head, 1);
        push(&head, 2);
        .....
        ....
    }
        
    /* Given a reference (pointer to pointer) to the head
       of a list and an int, push a new node on the front
       of the list. */
    void push(struct node** head_ref, int new_data)
    {
        /* allocate node */
        struct node* new_node = (struct node*) malloc(sizeof(struct node));
        .....
        .....
    }
    

    This is basically because, say a pointer was initially pointing to a memory location 0X100 and we want to change it to point it to some other location say 0X108. In such case pointer to pointer is passed.

提交回复
热议问题