Programming in C

(Barry) #1

202 Chapter 10 Character Strings


can be used to display the entire contents of the wordarray at the terminal.The printf
function assumes when it encounters the %sformat characters that the corresponding
argument is a character string that is terminated by a null character.
The two features just described were incorporated into the mainroutine of Program
10.3, which illustrates your revised concatfunction. Because you are no longer passing
the number of characters in each string as arguments to the function, the function must
determine when the end of each string is reached by testing for the null character. Also,
when str1is copied into the resultarray, you want to be certain notto also copy the
null character because this ends the string in the resultarray right there.You do need,
however, to place a null character into the resultarray afterstr2has been copied so as
to signal the end of the newly created string.

Program 10.3 Concatenating Character Strings
#include <stdio.h>

int main (void)
{
void concat (char result[], const char str1[], const char str2[]);
const char s1[] = { "Test " };
const char s2[] = { "works." };
char s3[20];

concat (s3, s1, s2);

printf ("%s\n", s3);

return 0;
}

// Function to concatenate two character strings

void concat (char result[], const char str1[], const char str2[])
{
int i, j;

// copy str1 to result

for ( i = 0; str1[i] != '\0'; ++i )
result[i] = str1[i];

// copy str2 to result
Free download pdf