在函数中分配内存,然后在外部使用它

Allocate memory in a function, then use it outside

我想在 malloc 函数内部分配内存,然后 return 缓冲区。然后我希望能够从函数外部 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

您的 allocate_mem 创建了 char * 但随后 return 变成了 char

return a char* 并将其存储为 char *buff 您的其余代码应该可以工作。

函数内的变量 buff 的类型为 char *。所以如果你想 return 指针那么函数必须有 return 类型 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 ?
}

主要你可以写

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 ?
}