be a little more specific? I assume it takes 2 args, but are they pointers to characters? Or should the function be a pointer to a function? If the args are char *, what are they terminated with, and what does the function return?
That will help.
MWB As always, I hope that helped!
Disclaimer:
Beware: Studies have shown that research causes cancer in lab rats.
Hello Jude,
I tried your srtcat function. It compiles fine but creates problems during runtime. With two strings ("strings" and "have been concatenated", I got the following.
" strings have been concatenated¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦ 8_e ".
If I add a third string I get a runtime failure on the screem.
Does anyone know how to fix this ??? I am trying this exercise myself and haven't solved it yet.
Thanks,
-John
this sounds like a class assignment. and so take a look at the size of ur destination string. is it large enough to receive the total data? a "string" in C must be terminated with a null "\0" or 0 (ascii val) character.. is that correct for ur strings??
and btw at the end of the second while loop in jude's function u might want to add *string1 = 0; to terminate the string..
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.
*/
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.