usage of double pointers as arguments

后端 未结 4 2057
北海茫月
北海茫月 2021-01-13 22:33

Please find the code snippet as shown below:

#include  

int My_func(int **); 

int main() 
{ 
     int a =5;
     int *p = &a;
     My_Fu         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-13 23:26

    int **p is a pointer to a pointer-to-int. My_Func(int **p) works by changing the value of integer that the pointer-to-int points to i.e. int a.

    Without changing the implementation, the function will not work with a pointer-to-int parameter int *p as there is a second level of indirection. In addition, you're setting the value to a local variable that is created on the stack. When the function is completed the memory used for the variable will be reclaimed, therefore making the value of a invalid.

    void My_Func(int **p)
    {
         int val = 100; // Local variable.
         int *Ptr = &val; // This isn't needed.
         *p = Ptr;
    } // val dissapears.
    

    Remove the second level of indirection and copy val by value instead of pointing to it:

    #include 
    
    void My_Func(int *p) 
    {
        int val = 100;
        *p = val;
    }
    
    int main(void) 
    {
        int a = 5;
        My_Func(&a);
        printf("The val of a is %d\n", a);
        return 0;
    }
    

提交回复
热议问题