【问题标题】:How to return a pointer as a function parameter如何将指针作为函数参数返回
【发布时间】:2011-03-12 23:56:51
【问题描述】:

我正在尝试从函数参数返回数据指针:

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

但是当我以如下方式调用函数时,数据地址变为零:

char *data = NULL;
if(dosomething(data)){
    // here data address = 0 ! (should be 10968998)
}

我做错了什么?

【问题讨论】:

  • 你真的在使用 C 还是在使用 C++(一些 cmets 表示你在谈论 C++ 引用)。
  • 我没有将其标记为 c++,因为我不知道这很重要,而且人们经常抱怨“那不是 c++ 那是 c”,因为我正在使用 malloc()...

标签: c++ c pointers


【解决方案1】:

你是按价值传递的。 dosomething 修改其本地的 data 副本 - 调用者永远不会看到。

使用这个:

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

char *data = NULL;
if(dosomething(&data)){
}

【讨论】:

  • 哦该死的......我明白了,一个指向指针的指针......但是没有其他方法可以做到这一点吗?我看到函数中没有 & 的指针,是否可以这样转换我的函数工作? (我喜欢没有 & 因为它不容易出错)
  • 你可以做char * dosomething(char *) 并返回新的指针。
  • 但我想从函数返回布尔值,我的意思是我是否可以调用函数dosomething(data) 而不是dosomething(&data)?也许在 C++ 中?
  • 在 C++ 中是 - 然后使用 bool dosomething (char * & data) - 通过引用传递
  • 在这种情况下调用者是否有责任释放指针? (删除数据等)?
【解决方案2】:
int changeme(int foobar) {
  foobar = 42;
  return 0;
}

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

你的 sn-p 也是这样。

C 通过值传递一切

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 2020-06-11
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多