There are four ways to return string functions in C + +:
1. Using heap space, return the heap address of the application, and pay attention to releasing 2. The function parameter passes the pointer, which returns the pointer 3. Returns the static variable (shared) 4 defined within the function. Return global variable
1. Use heap space, return the heap address of the application, pay attention to releaseIn fact, to return a valid pointer, the tail variable is invalid after exiting. Use allocated memory, address is valid
Char *fun ()
{
char* s = (char*) calloc (M, sizeof (char*)) ;
If (s)
strcpy (S, "abc");
return s;
But this approach needs to be noted, and must be free from using the address that will be returned
2. The function parameter passes the pointer, returns the pointerThe address is passed into the
char* Fun (char*s)
{
if (s)
strcpy (S, "abc");
return s;
This way call should be aware that the size assigned to S is sufficient. You can do this:
char* Fun (char*s, int len)
{
if (s)
{
strncpy (s), ABC, len-1);
S[len-1] = 0;
}
return s;
3. Using local static variables
char* Fun ()
{
static char s[100];
strcpy (S, "abc");
return s;
This approach requires attention, do not modify the returned string, because it is a shared address, changes to it will be reflected to each caller. You can do this:
Const char* Fun ()
{
static char s[100];
strcpy (S, "abc");
return s;
4. Use global variables
Char g_s[100];
char* Fun ()
{
strcpy (g_s, "abc");
return s;
Also, be aware of the maximum space that this variable can store.