这是引用这个问题: Why is a pointer to pointer needed to allocate memory in this 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);
}
最佳答案
int* three(int * p)
{
p = (int *) malloc(sizeof(int));
*p=3;
return p;
}
因为在这里您要返回指针 p
的副本,并且该指针现在指向有效内存,其中包含值 3。
您最初将 p
的一个副本 作为参数传入,因此您不是在更改传入的那个,而是一个副本。然后您返回该副本并分配它。
从评论来看,这是一个非常有效的观点,这也同样有效:
int* three()
{
//no need to pass anything in. Just return it.
int * p = (int *) malloc(sizeof(int));
*p=3;
return p;
}
关于c - 从函数返回指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12496346/