Programming in C

(Barry) #1
Variable-Length Character Strings 203

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

// Terminate the concatenated string with a null character

result [i + j] = '\0';
}


Program 10.3 Output


Test works.


In the first forloop of the concatfunction, the characters contained inside str1are
copied into the resultarray until the null character is reached. Because the forloop
terminates as soon as the null character is matched, it does not get copied into the
resultarray.
In the second loop, the characters from str2are copied into the resultarray direct-
ly after the final character from str1.This loop makes use of the fact that when the pre-
vious forloop finished execution, the value of iwas equal to the number of characters
in str1, excluding the null character.Therefore, the assignment statement


result[i + j] = str2[j];


is used to copy the characters from str2into the proper locations of result.
After the second loop is completed, the concatfunction puts a null character at the
end of the string. Study the function to ensure that you understand the use of iand j.
Many program errors when dealing with character strings involve the use of an index
number that is off by 1 in either direction.
Remember, to reference the first character of an array, an index number of 0 is used.
In addition, if a character array stringcontains ncharacters, excluding the null byte,
then string[n – 1]references the last (nonnull) character in the string, whereas
string[n]references the null character. Furthermore,stringmust be defined to con-
tain at least n + 1characters, bearing in mind that the null character occupies a location
in the array.
Returning to the program, the mainroutine defines two chararrays,s1and s2, and
sets their values using the new initialization technique previously described.The array s3
is defined to contain 20 characters, thus ensuring that sufficient space is reserved for the
concatenated character string and saving you from the trouble of having to precisely cal-
culate its size.
The concatfunction is then called with the three strings s1,s2,and s3as arguments.
The result, as contained in s3after the concatfunction returns, is displayed using the %s
format characters. Although s3is defined to contain 20 characters, the printffunction
only displays characters from the array up to the null character.


Program 10.3 Continued

Free download pdf