C language implementation Four ways to return string functions _c language

Source: Internet
Author: User

Objective

There are four ways to return string functions in the C language, respectively:

    1. Use heap space, return the heap address of the application, pay attention to release
    2. function parameter passes the pointer and returns the pointer
    3. Returns the static variables defined within a function (shared)
    4. 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.

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.