There are four ways: 1. Using heap space, return the requested heap address, and note release 2. The function parameter passes a pointer that returns the pointer 3. Returns a static variable (shared) 4 defined within a function. Returning a global variable is actually going to return a valid pointer, which is invalid when the trailing variable exits.
Using allocated memory, the address is valid
Char *fun ()
{
char* s = (char*) calloc (n, sizeof (char*));
if (s)
strcpy (S, "abc");
return s;
}
However, this method needs to be noted that the address to be returned by the use will be free
The address is passed in by the input parameter
char* Fun (char*s)
{
if (s)
strcpy (S, "abc");
return s;
}
This method of invocation is important to note that the size allocated to S is sufficient.
Can do this:
char* Fun (char*s, int len)
{
if (s)
{
strncpy (S, "abc", LEN-1);
S[len-1] = 0;
}
return s;
}
or use local static variables
char* Fun ()
{
static Char s[100];
strcpy (S, "abc");
return s;
}
This way, it is important to note that the returned string is not modified, because it is a shared address, and changes to it will be reflected to each caller. Can do this:
Const char* Fun ()
{
static Char s[100];
strcpy (S, "abc");
return s;
}
There is also the use of global variables
Char g_s[100];
char* Fun ()
{
strcpy (g_s, "abc");
return s;
}
Also, be aware of the maximum amount of space this variable can store.
Four implementation methods of returning string functions in C language