How do pointer to pointers work in C?

前端 未结 14 1612
渐次进展
渐次进展 2020-11-22 02:03

How do pointers to pointers work in C? When would you use them?

14条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 02:56

    Consider the below figure and program to understand this concept better.

    As per the figure, ptr1 is a single pointer which is having address of variable num.

    ptr1 = #
    

    Similarly ptr2 is a pointer to pointer(double pointer) which is having the address of pointer ptr1.

    ptr2 = &ptr1;
    

    A pointer which points to another pointer is known as double pointer. In this example ptr2 is a double pointer.

    Values from above diagram :

    Address of variable num has : 1000
    Address of Pointer ptr1 is: 2000
    Address of Pointer ptr2 is: 3000
    

    Example:

    #include 
    
    int main ()
    {
       int  num = 10;
       int  *ptr1;
       int  **ptr2;
    
       // Take the address of var 
       ptr1 = #
    
       // Take the address of ptr1 using address of operator &
       ptr2 = &ptr1;
    
       // Print the value
       printf("Value of num = %d\n", num );
       printf("Value available at *ptr1 = %d\n", *ptr1 );
       printf("Value available at **ptr2 = %d\n", **ptr2);
    }
    

    Output:

    Value of num = 10
    Value available at *ptr1 = 10
    Value available at **ptr2 = 10
    

提交回复
热议问题