【发布时间】:2012-04-29 22:26:42
【问题描述】:
我在使用指向字符的指针时遇到了这个问题:
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;
}
上面的代码是正确的,但我不明白为什么在这里使用指向指针 char** p 的指针?为什么只使用指向 char 的指针呢?所以我把这个sn-p改成下面发现它不起作用,谁能告诉我为什么?谢谢!
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;
}
【问题讨论】:
-
p是一个局部变量。*p不是。 -
@cnicutar,这里有很好的例子,谢谢!