C++ Topics and Explanations
Concatenates Char string

[ Follow Ups ] [ Post Follow Up ] [ C++ Topics and Explanations ]

Posted by Kwan Chan on December 08, 1999 at 02:49:48:

Before I understand the pointer, I don't know how the function prototypes under string.h work. Usually we use strcat to concatenate two different character string, but most people do not know how it work. In chapter 5 of Deitel & Deitel, char *strcat( char *s1, const char *2), it describe append the string s2 to the string of s1.

s1 is a pointer to a destination string, and s2 is pointer to the source string. The source strings are to be appended to the end of the destination string. As Deitel & Deitel explained, the first characters of s2 overwrites the terminating null character of s1.

After I understand the pointer I wrote a simple function call strcat3 that concatenates 3 c-string.

Char *strcat3 ( char *s1, char *s2, char *s3 ) {

Char *temp;

For (temp = s1; *temp != '\0'; temp++)

For ( ; *s2 != '\0'; )
**temp++ = *s2++;

for ( ; *s3 != '\0'; )
**temp++ = *s3++;

*temp = '\0';

return ( s1 );
}

The function strcat3 takes 3 parameters, and return the pointer to the destination string.

The first for statement place s1 (a pointer to a destination string) to pointer temp until null terminator. The second and third for statement place char into temp until null terminator. Then add null terminator into pointer temp and return char s1. Finally I know how strcat work.



Follow Ups:


Post a Follow Up:

Name:
E-Mail:

Subject:

Comments:


[ Follow Ups ] [ Post Follow Up ] [ C++ Topics and Explanations ]