malloc memory to a pointer to pointer

后端 未结 4 1851
心在旅途
心在旅途 2021-01-24 01:02

I have came across this problem when using pointer to pointer to a char:

void setmemory(char** p, int num)
{
    *p=(char*)malloc(num);
}

    void test(void)
           


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-24 01:48

    You are only setting the local variable *p here. Remember you are getting a pointer to data, not a pointer-to-pointer-to-data.

    Think of it like this:

    First case:

    int a;
    
    foo(a); // Passes a
    void foo(int b)
    {
      b = 4;    // This only changes local variable, has no effect really
    }
    

    Second case:

    int a;
    foo(&a); // Passes *a
    
    void foo(int *b)
    {
      *b = 4; // This changes the contents of a. As you can see we have not changed the original pointer!
      b = 4; // This changes our local copy of the pointer, not the pointer itself, like in the first case!
    }
    

    Third case

    int *ptr;
    foo(&ptr); // Passes **ptr
    
    void foo(int **b)
    {
      **b = 4; // This changes the data of the passed pointer
      *b = 4; // This changes the passed pointer itself, i.e. it changes ptr. This is what test() is doing, the behavior you are looking for!
      b = 4; // This changes our local copy of a variable, just like the first case!
    }
    

提交回复
热议问题