你的char数组变量out只存在内部函数体。
当您从函数返回时,out缓冲区的内容将无法再访问,它仅是函数的本地内容。
如果要将函数中的某个字符串返回给调用者,则可以在函数内部动态分配该字符串(例如使用malloc()),并将指向该字符串的指针返回给调用者,例如
char* gen(void)
{
char out[256];
sprintf(out, ...);
/*
* This does NOT work, since "out" is local to the function.
*
* return out;
*/
/* Dynamically allocate the string */
char* result = malloc(strlen(out) + 1) /* +1 for terminating NUL */
/* Deep-copy the string from temporary buffer to return value buffer */
strcpy(result, out);
/* Return the pointer to the dynamically allocated buffer */
return result;
/* NOTE: The caller must FREE this memory using free(). */
}
另一个更简单的选择是将out缓冲区指针char*与缓冲区大小一起作为参数传递(以避免缓冲区溢出)。
在这种情况下,您的函数可以将字符串直接格式化为作为参数传递的目标缓冲区:
/* Pass destination buffer pointer and buffer size */
void gen(char* out, size_t out_size)
{
/* Directly write into caller supplied buffer.
* Note: Use a "safe" function like snprintf(), to avoid buffer overruns.
*/
snprintf(out, out_size, ...);
...
}
请注意,您在问题标题中明确指出了“ C”,但添加了[c++]标签。如果你可以使用C ++,以最简单的做法是使用一个字符串类像std::string(并让它管理所有的字符串缓冲区的内存分配/清理)。