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)
{
char* str=NULL;
setmemory(&str,100);
strcpy(str,"hello");
printf(str);
}
int main()
{
test();
return 0;
}
The code above is correct,but I can’t figure it out why using a pointer to a pointer char** p here? Why just using a pointer to a char instead? so I change this snippet into below and found it not working ,can anyone tell me why? thanks!
void setmemory(char* p, int num)
{
p=(char*)malloc(num);
}
void test(void)
{
char* str=NULL;
setmemory(str,100);
strcpy(str,"hello");
printf(str);
}
int main()
{
test();
return 0;
}
One thing to note here is – When we say pointers, we generally tend to think in terms of
pass by referencebut not necessarily. Even pointers can bepassed by valuechar* stris local totestandchar* pis local tosetmemory. So the changes you do insetmemorywill not be visible intestif you dont send a pointer to a pointer.You can make it work with a single pointer like this
Note that in
setmemorywe 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