|
|
|
|
|
|
|
The strcpy routine is important because aggregate assignment with the = operator is not allowed. In the following code fragment, we show the wrong way and the right way to perform a string copy. |
|
|
|
|
|
|
|
|
#include <string.h>
.
.
.
char myStr[100];
.
.
.
myStr = "Abracadabra"; // No
strcpy(myStr, "Abracadabra"); // Yes |
|
|
|
|
|
|
|
|
In strcpy's parameter list, the destination string is the one on the left, just as an assignment operation transfers data from right to left. It is the caller's responsibility to make sure that the destination array is large enough to hold the result. |
|
|
|
|
|
|
|
|
The strcpy function is technically a value-returning function; it not only copies one string to another, it also returns as a function value the base address of the destination array. The reason why the caller would want to use this function value is not at all obvious, and we don't discuss it here. Programmers nearly always ignore the function value and simply invoke strcpy as if it were a void function (as we did above). You may wish to review the Background Information box in Chapter 8 entitled "Ignoring a Function Value." |
|
|
|
|
|
|
|
|
The strcmp function is used for comparing two strings. The function receives two strings as parameters and compares them in lexicographic order (the order in which they would appear in a dictionary). Specifically, corresponding characters in the strings are compared one by one, starting with the first. The first unequal pair of characters determines the order. For example, "Hello" compares less than "Helvetica". The first three characters are the same in both strings, but 'l' compares less than 'v' in both ASCII and EBCDIC. Given the function call strcmp (str1, str2), the function returns one of the following int values: a negative integer, if str1 < str2 lexicographically; the value 0, if str1 = str2; or a positive integer, if str1 > str2. The precise values of the negative integer and the positive integer are unspecified. You simply test to see if the result is less than zero, zero, or greater than zero. Here is an example: |
|
|
|
|
|
|
|
|
if (strcmp(str1, str2) < 0) // If strl is less than str2 ...
.
.
. |
|
|
|
|
|