malloc memory to a pointer to pointer

后端 未结 4 1879
心在旅途
心在旅途 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:50

    One thing to note here is - When we say pointers, we generally tend to think in terms of pass by reference but not necessarily. Even pointers can be passed by value

    char* str is local to test and char* p is local to setmemory . So the changes you do in setmemory will not be visible in test if you dont send a pointer to a pointer.

    You can make it work with a single pointer like this

     char * setmemory(char* p, int num) // p is a new pointer but points at the same
                                        // location as str
    {
        p=(char*)malloc(num); // Now, 'p' starts pointing at a different location than 'str'
        strcpy(p ,"hello");  // Copy some data to the locn 'p' is pointing to
        return p; // Oops. The poor `str` is still pointing at NULL :( 
                  // Send him the address of the newly allocated area
    }
    
    void test(void)
    {
        char* str=NULL;
        str=setmemory(str,100); // We are passing a pointer which is pointing to NULL
    
        printf(str); //Now str points to the alloced memory and is happy :)
    }
    
    int main()
    {
        test();
        return 0;
    }
    

    Note that in setmemory we are returning a local pointer, but it is not a problem ( no dangling pointer problems ) as this pointer points to a location on heap and not on stack

提交回复
热议问题