简体   繁体   English

如何将指针作为函数参数返回

[英]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)
}

What am I doing wrong? 我究竟做错了什么?

You're passing by value. 你正在经历价值。 dosomething modifies its local copy of data - the caller will never see that. dosomething修改其本地data副本 - 调用者永远不会看到它。

Use this: 用这个:

bool dosomething(char **data){
    int datasize = 100;
    *data = (char *)malloc(datasize);
    return 1;
}

char *data = NULL;
if(dosomething(&data)){
}
int changeme(int foobar) {
  foobar = 42;
  return 0;
}

int  main(void) {
  int quux = 0;
  changeme(quux);
  /* what do you expect `quux` to have now? */
}

It's the same thing with your snippet. 你的代码片段也是如此。

C passes everything by value. C按值传递所有内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM