Four implementation methods of returning string functions in C language

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.