Your char
array variable out
exists only inside the function's body.
When you return from the function, the content of out
buffer can't be accessed anymore, it's just local to the function.
If you want to return some string from your function to the caller, you can dynamically allocate that string inside the function (e.g. using malloc()
) and return a pointer to that string to the caller, e.g.
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(). */
}
Another simpler option would be to pass the out
buffer pointer as a char*
parameter, along with a buffer size (to avoid buffer overruns).
In this case, your function can directly format the string into the destination buffer passed as parameter:
/* 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, ...);
...
}
Note that you explicitly stated "C" in your question title, but you added a [c++]
tag. If you can use C++, the simplest thing to do is to use a string class like std::string
(and let it manage all the string buffer memory allocation/cleanup).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…