Basic C language series-four implementation methods for returning string functions

Source: Internet
Author: User
There are four methods: 1. Use the heap space and return the requested heap address. Pay attention to Release 2. Function parameters pass a pointer and 3 is returned. Returns the static variable (SHARE) 4 defined in the function. Return the global variable ****************** from csdn **************** * ************* is actually to return a valid pointer, the tail variable is invalid after exiting.

Use the allocated memory. The address is valid.
Char * Fun ()
{
Char * s = (char *) calloc (100, sizeof (char *));
If (s)
Strcpy (S, "ABC ");
Return S;
}
However, in this way, you must use this method to free up the returned address.

input the address from the input parameter
char * Fun (char * s)
{< br> If (s)
strcpy (S, "ABC");
return s;
}< br> note that the size allocated to S is sufficient when calling this method.
you can do this:
char * Fun (char * s, int Len)
{< br> If (s)
{< br> strncpy (S, "ABC", len-1);
S [len-1] = 0;
}< br> return S;
}

Or use local static variables
Char * Fun ()
{
Static char s [100];
Strcpy (S, "ABC ");
Return S;
}
Do not modify the returned string in this way. Because it is a shared address, the modification will be reflected to each caller. You can do this:
Const char * Fun ()
{
Static char s [100];
Strcpy (S, "ABC ");
Return S;
}

Another way is to use global variables.
Char G_s [100];
Char * Fun ()
{
Strcpy (G_s, "ABC ");
Return S;
}
Pay attention to the maximum storage space of this variable.

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.