Mar 18, 2010 at 8:10pm Mar 18, 2010 at 8:10pm UTC
I am attempting to write a concatenate function taking two chars in the form
sc1(char * s1, const char* s2);
The code for the function I have defined as:
1 2 3 4 5 6 7 8 9 10 11
char * stringCat1(char * s1, const char * s2){
int i = 0, z = 0;
while (s1[i] != '\0' ){
i++;
}
for (z = 0; s2[z] != '\0' ; z++){
s1[i + z] = s2[z];
}
return s1;
}
This almost works - however when a concat strings are output I see something like:
1 2
stringCat1(s1, education): schooleducation╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠
╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠^_≈▬╝ⁿ1
Why do I see all the trailing chars? Please no responses telling me to implement standard library functions. Also, I know how to accomplish this with pointers.
Regards,
RC325
Last edited on Mar 18, 2010 at 9:39pm Mar 18, 2010 at 9:39pm UTC
Mar 18, 2010 at 8:24pm Mar 18, 2010 at 8:24pm UTC
Show a main function that makes a call to the stringCat1 function. It appears that you end up with something that has no terminating NULL. Therefore when you try to print the data the code executes way beyond the end of the array until it happens to find a 0 in memory. After the second for loop you didn't bother to add a '\0' so you are returning a pointer to a non-null terminated character array.
Last edited on Mar 18, 2010 at 8:25pm Mar 18, 2010 at 8:25pm UTC
Mar 18, 2010 at 9:35pm Mar 18, 2010 at 9:35pm UTC
Here is the main function requested:
View line numbers 21-24.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
int main()
{
char s1[ 100 ];
char * s2 = "education" ;
char * s3 = "school" ;
// Test stringLength functions
cout << "stringLength(" << s2 << "): "
<< stringLength1( s2 ) << endl;
cout << "stringLength(" << s3 << "): "
<< stringLength2( s3 ) << endl;
// Test stringCopy functions
cout << "stringCopy1(s1, " << s2 << "): "
<< stringCopy1( s1, s2 ) << endl;
cout << "stringCopy2(s1, " << s3 << "): "
<< stringCopy2( s1, s3 ) << endl;
// Test stringCat functions
cout << "stringCat1(s1, " << s2 << "): "
<< stringCat1( s1, s2 ) << endl;
cout << "stringCat2(s1, " << s3 << "): "
<< stringCat2( s1, s3 ) << endl;
system("pause" );
return 0; // indicates successful termination
} // end main
Regards,
RC325
Last edited on Mar 18, 2010 at 9:37pm Mar 18, 2010 at 9:37pm UTC