如何将指针作为函数参数返回 [英] How to return a pointer as a function parameter
本文介绍了如何将指针作为函数参数返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从函数参数返回数据指针:
I'm trying to return the data pointer from the function parameter:
bool dosomething(char *data){
int datasize = 100;
data = (char *)malloc(datasize);
// here data address = 10968998
return 1;
}
但是当我以以下方式调用该函数时,数据地址将更改为零:
but when I call the function in the following way, the data address changes to zero:
char *data = NULL;
if(dosomething(data)){
// here data address = 0 ! (should be 10968998)
}
我在做什么错了?
推荐答案
您正在按值传递. dosomething
修改其data
的本地副本-调用者将永远不会看到它.
You're passing by value. dosomething
modifies its local copy of data
- the caller will never see that.
使用此:
bool dosomething(char **data){
int datasize = 100;
*data = (char *)malloc(datasize);
return 1;
}
char *data = NULL;
if(dosomething(&data)){
}
这篇关于如何将指针作为函数参数返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文