【问题标题】:Allocate memory in a function, then use it outside [closed]在函数中分配内存,然后在外部使用它[关闭]
【发布时间】:2020-12-07 23:38:22
【问题描述】:

我想用malloc 在函数内部分配内存,然后返回缓冲区。然后我希望能够从函数外部将strcpy 字符串放入该缓冲区。

这是我当前的代码

#include <stdlib.h>
#include <string.h>

char allocate_mem(void) {
    char *buff = malloc(124); // no cast is required; its C

    return buff // return *buff ?
}

int main(int argc, char const *argv[])
{
    char buff = allocate_mem();
    strcpy(buff, "Hello World");
    free(buff);
    return 0;
}
// gcc (Ubuntu 9.3.0-10ubuntu2) 9.3.0

【问题讨论】:

  • 错误的原型使用char *allocate_mem(void)
  • 还有char * buff = allocate_mem();
  • 阿利希巴赫曼。省时间。在您的编译器上启用更多警告,以快速获得有问题的反馈。比 SO 快得多。
  • 我并不是说你没有进步之类的,但 2 天后,你需要更多阅读文档、教程和示例。如果您在这里用 C(或 C++、python 或任何成熟的语言)提出问题,它必须是一个非常好的问题。
  • @Jean-FrançoisFabre 我明白,我保证会改进我的问题。感谢您的宝贵时间。

标签: c dynamic-memory-allocation c-strings


【解决方案1】:

函数中的变量buff 的类型为char *。所以如果你想返回指针,那么函数必须有返回类型char *

char * allocate_mem(void) {
    char *buff = malloc(124); // no cast is required; its C

    return buff // return *buff ?
}

主要是你必须写

char *buff = allocate_mem();

注意不要在函数中使用幻数124

更有意义的函数可能如下所示

char * allocate_mem( const char *s ) {
    char *buff = malloc( strlen( s ) + 1 ); // no cast is required; its C
    
    if ( buff ) strcpy( buff, s );

    return buff // return *buff ?
}

而在 main 你可以写

char *buff = allocate_mem( "Hello World" );
//...
free(buff);

另一种方法是使用一个整数值作为参数,该整数值将指定分配内存的大小。例如

char * allocate_mem( size_t n ) {
    char *buff = malloc( n ); // no cast is required; its C

    return buff // return *buff ?
}

【讨论】:

    【解决方案2】:

    您的allocate_mem 创建char *,但随后返回char

    返回 char* 并将其存储为 char *buff 其余代码应该可以工作。

    【讨论】:

      猜你喜欢
      • 2017-06-16
      • 1970-01-01
      • 2012-08-18
      • 2017-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      相关资源
      最近更新 更多