Last night and @buptpatriot discussed the question of the function return pointer (malloc generated), referring to string concatenation, to make a summary.
[CPP]View Plaincopyprint?
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- Char *join1 (char *, char*);
- void Join2 (char *, char *);
- Char *join3 (char *, char*);
- int main (void) {
- char a[4] = "abc"; //char *a = "abc"
- char b[4] = "Def"; //Char *b = "def"
- char *c = Join3 (A, b);
- printf ("concatenated String is%s\n", c);
- Free (c);
- c = NULL;
- return 0;
- }
- /* Method One, do not change the string A, B, by malloc, generate a third string C, return the local pointer variable */
- Char *join1 (char *a, char *b) {
- char *c = (char *) malloc (strlen (a) + strlen (b) + 1); //local variables, requesting memory with malloc
- if (c = = NULL) exit (1);
- char *TEMPC = c; //Save the first address
- While (*a! = ')} {
- *c++ = *a++;
- }
- While ((*c++ = *b++)! = ' + ' ) {
- ;
- }
- //Note that at this point the pointer C has pointed to the end of the string after stitching!
- return TEMPC; The //return value is a pointer variable for the local malloc request, which is required after the function call ends
- }
- /* Method Two, get rid of the string directly a,*/
- void Join2 (char *a, char *b) {
- //Note that if a A, B in the main function defines a string constant (as follows):
- //char *a = "abc";
- //char *b = "Def";
- //Then the join2 is not feasible.
- //must be defined like this:
- //char a[4] = "ABC";
- //char B[4] = "Def";
- While (*a! = ')} {
- a++;
- }
- While ((*a++ = *b++)! = ' + ' ) {
- ;
- }
- }
- /* Method Three, call C library function, */
- char* join3 (char *s1, char *s2)
- {
- char *result = malloc (strlen (S1) +strlen (S2) +1); //+1 for the Zero-terminator
- //in Real code would check for errors on malloc here
- if (result = = NULL) exit (1);
- strcpy (result, S1);
- strcat (result, S2);
- return result;
- }
3 Ways to stitch the "C Language Learning Notes" string.