C++ 函数是否可能使用其参数返回指针?

C++ 函数是否可能使用其参数返回指针?,c++,function,pointers,C++,Function,Pointers,我有一个动态分配内存并将地址保存在其本地指针中的函数。我希望调用者函数中有这个地址。 是的,我可以使用return来实现。但是可以使用函数的参数来实现吗 #include<bits/stdc++.h> using namespace std; void getAddress(int *ptr){ int *temp=(int*)malloc(sizeof(int)); ptr=temp; cout<<ptr<<endl; } int

我有一个动态分配内存并将地址保存在其本地指针中的函数。我希望调用者函数中有这个地址。 是的,我可以使用return来实现。但是可以使用函数的参数来实现吗

#include<bits/stdc++.h>
using namespace std;
void getAddress(int *ptr){
    int *temp=(int*)malloc(sizeof(int));
    ptr=temp;
    cout<<ptr<<endl;
} 
int main(){
    int *ptr=NULL;
    cout<<ptr<<endl;
    getAddress(ptr);
    cout<<ptr<<endl;
    return 0;
}
output : 
0
0x6fa010
0

Expected output :
0
0x6fa010
0x6fa010

是的,您可以通过参考传递:

void getAddress(int *&ptr){
//                   ~
    int *temp=(int*)malloc(sizeof(int));
    ptr=temp;
    cout<<ptr<<endl;
} 
OT:临时工不是多余的吗?
OT2:别忘了释放main末尾的指针。

从风格上讲,如果在函数体中分配内存,最好返回分配的指针,因为C标准库函数就是这样做的。但可以将其作为参数传递,但需要额外的间接级别:

在函数体中,以及

getAddress(&ptr);
在呼叫站点。另一种方法是通过引用传递指针:

void getAddress(int *&ptr){
//                   ~
    int *temp=(int*)malloc(sizeof(int));
    ptr=temp;
    cout<<ptr<<endl;
} 

这需要更少的更改,可能以牺牲调用站点的可读性为代价。

有很多不同的方法可以做到这一点,哪种方法最好取决于应用程序。在这种情况下,返回指针显然更好。旁注:实际上不太可能需要使用malloc,所以请尽量不要使用。@DavidSchwartz-重复的段落清楚地说明了这个问题在这里已经有了答案:。这是链接上公认的答案。@DavidSchwartz-这是对这个问题的一个很好的回答。我稍微解释了一下OP的问题,我可以使用functions参数更改参数吗。链接的dup询问为什么参数中的更改在参数上不可见。在这两种情况下,答案都是一样的。OT3:不要在C++中使用malloc或free。OT4:为什么要动态分配一个很小的int?
getAddress(&ptr);
void getAddress(int*& ptr){