Several implementation methods of C + + return string function __jquery

Source: Internet
Author: User
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.
Related Article

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.