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



我想用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

函数中的变量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 ?
}

总的来说,你可以写

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

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

返回一个char*并将其存储为char *buff,您的代码的其余部分应该可以工作。

相关内容

最新更新