[M-5]
Write function stringConcat( char *s1,
char *s2)
that appends the contents of the string s2
to
the end of the string s1
. The null character that ends s1
is overwritten with the first character in s2
and a new null character
is place at the end of the combined strings. String s1
is assumed
to be contained in a buffer that has enough room for the combined length of
the strings. The string s2
is not affected. The function returns
the address of the first byte of s1
(which is the value of
s1
that is passed into the function.) This function is similar to the
standard strcat()
function. Here is a picture that shows the operation
of the function:
The variable p
is local to the function so
that the value in s1 can be returned,
as per specifications. Here is a testing program:
#include <stdio.h> #include <stdlib.h> void stringCopy( char *copy, char *source ) { } char *stringConcat( char *s1, char *s2 ) { } int main() { char buffer[ 100 ]; char *trialsA[] = { "The game is", "Genius is an infinite capacity", "So is", "", "", "As always,\n", "Will\ttabs\t", "For great fun, " }; char *trialsB[] = { " afoot!", " for taking pains.", " programming.", "", "concatenated to an empty string", "linefeeds should\nwork.", "confuse\tthings?", " change the buffer size to 5!" }; int j ; for ( j=0; j<sizeof(trialsA)/sizeof(char *); j++ ) { stringCopy( buffer, trialsA[j] ); stringConcat( buffer, trialsB[j] ); printf("%s\n", buffer ); } return 0; }
stringCopy()
is used in the testing program and also might be used
in stringConcat().