Programmer --- C language details 5

Source: Internet
Author: User

Programmer --- C language details 5
Main Content: String memory allocation, merge two strings

# Include

 
  
# Include

  
   
Int main (int argc, char * argv []) {/** string operation: Memory Allocation * string s and t, to connect these two strings into a single string r */char * s = "abc"; char * t = "def"; // Method 1: disadvantages: 1. You cannot determine where r points to. // 2. You do not know whether the memory space pointed to by r can accommodate the size of a string, in addition, the memory used by other programs is allocated first, instead of the memory used by other programs # if 0 char * r; strcpy (r, s); strcat (r, t ); printf ("% s \ n", r); # elseif 0 // Method 2: disadvantages: the size of the s and t strings should not exceed the r size to work normally. char r [100]; // the size of strcpy (r, s) is specified in advance; strcat (r, t); printf ("% s \ n", r); # elseif 0 // method 3: disadvantages: 1. the malloc function may not provide the requested memory/ /2. release immediately after the r allocation is completed. // 3. malloc does not allocate enough memory. The string needs '\ 0' to end char * r; r = malloc (strlen (s) + strlen (r); strcpy (r, s); strcat (r, t); printf ("% s \ n ", r); # else // Method 4: char * r; r = malloc (strlen (s) + strlen (r) + 1 ); // allocate memory for the string '\ 0' if (! R) // determine whether the allocation is successful {printf ("malloc failed! \ N "); exit (1) ;}strcpy (r, s); strcat (r, t); printf (" % s \ n ", r ); free (r); // releases the memory # endif return 0 ;}

  

 
Output:


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.