malloc memory to a pointer to pointer

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

    The orignal code is passing in the location of where the caller wants the string pointer put. If you pass in only a 'char*', the caller will pass by value the contents of the callers location - probably some uninitialized value.

    If the callee has to return a string, or other indirected struct, you need both asterisks so that the callee can return a pointer into the callers pointer variable.

    Does that make sense? It did to me, but then again, I wrote it.

提交回复
热议问题