Objective
There are four ways to return string functions in the C language, respectively:
- Use heap space, return the heap address of the application, pay attention to release
- function parameter passes the pointer and returns the pointer
- Returns the static variables defined within a function (shared)
- Return global variable
Let's take a look at the detailed introduction
In 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
The 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;
or use 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;
There is also a use of 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.
Summarize
The above is the entire content of this article, I hope the content of this article for everyone to learn or use C language can help, if there is doubt you can message exchange.