Shail is right. In Jude's code, in last line there is no '\0' character to close the string so the output is incorrect. Second, the algorithm is right, but in implementation using C, it's NOT SAFE because we store data beyond string1 and that could overwrite some information or other variable data.
#include <alloc.h>
// ...
void mySecondStrCat(char * str1, char * str2)
{
int str1Len = 0;
int str2Len = 0;
while ( str1++ ) str1Len++; // get the length of str1.
while ( str2++ ) str2Len++; // get the length of str2.
// create a temporary variable to hold the old string
// of str1.
char *temp = (char *) malloc(str1Len + 1);
// move back the str1 to the first character (b'cuz we
// have moved it to count the str1Len) and while moving
// backwards, copy it to temp.
for (register int i = str1Len - 1; i >=0 ; i--) {
temp
= str1;
temp--; str1--;
}
temp[str1Len] = '\0';
free( str1 ); // clean the str1 contents (although you
// didn't allocate it using malloc, it's
// okay
.
// allocate the enough space for concattenating str1
// with str2.
str1 = (char *) malloc(str1Len + str2Len + 1);
// move back str2 to the first character (b'cuz we also
// moved it to the last character for counting str2Len)
for (i = str2Len - 1; i >= 0; i--)
str2--;
// Now copy the temp to str1 and concat it
// with str2.
int j = 0;
for (i = 0, j = 0; i < str1Len; i++, j++)
str1[j] = temp;
for (i = 0; i < str2Len; i++, j++)
str1[j] = str2;
str1[j] = '\0'; // close the string.
}
/**
* Note: I haven't try to run this function yet, but I think
* thats the safer algorithm for the process.
* Maybe someone else can give more better solution.
*/