这是在参考这个问题:why pointer to pointer is needed to allocate memory in function从函数返回一个指针
的问题的答案解释了为什么这不起作用:
void three(int * p)
{
p = (int *) malloc(sizeof(int));
*p=3;
}
void main()
{
int *p = 0;
three(p);
printf("%d",*p);
}
...但这个工程:
void three(int ** p)
{
*p = (int *) malloc(sizeof(int));
**p=3;
}
void main()
{
int *p = 0;
three(&p);
printf("%d",*p);
}
我的问题是,这也可以通过从函数返回一个指针。这是为什么?
int* three(int * p)
{
p = (int *) malloc(sizeof(int));
*p=3;
return p;
}
void main()
{
int *p = 0;
p=three(p);
printf("%d",*p);
}
传递指针在这里没有意义,因为malloc会覆盖它。 –
@KingsIndian:我会说,相反:在这里分配内存毫无意义,因为无论如何都会传递指针。 :P – netcoder
@netcoder:这取决于是否需要调用者分配。 –