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;
}
pis a local variable.*pis not.