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: