Last night and @buptpatriot discussion function return pointer (malloc generated) problem, refer to string concatenation, make a summary.
#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, does not change the string a,b, generates a third string C through the malloc, returns the local pointer variable */char *join1 (char *a, char *b) {char *c = (char *) malloc (strlen (a) + Strlen (b) + 1);
local variable, using malloc to request memory if (c = NULL) exit (1); char *TEMPC = c;
Save the first address while (*a!= ' ") {*c++ = *a++;
while ((*c++ = *b++)!= ' ") {;
/Note that the pointer C already points to the end of the string after the concatenation. Return tempc;//returned value is a local malloc application of the pointer variable, the function call after the end of Free}/* Method Two, directly to get rid of the string A, this method is wrong, see message board/void Join2 (char *a, char *b) {//Note, if
In the main function a,b defines the string constants (as follows)://char *a = "abc";
Char *b = "Def";
Then the join2 is not workable.
This must be defined as://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 Zer
O-terminator//in Real code you would check for errors in malloc here if (result = NULL) exit (1);
strcpy (result, S1);
strcat (result, S2);
return result;
}
Reference: Http://stackoverflow.com/questions/8465006/how-to-concatenate-2-strings-in-c
http://www.cplusplus.com/reference/cstdlib/malloc/
Http://www.programmingspark.com/2012/02/c-program-to-concatenate-two-strings.html
Update
---------
The message, @napoleon_1815 classmate said very right, my join2 method is wrong, thank you for correcting.