Copying and Comparing Cstrings

  1. Since cstrings are arrays, many of the usual operations, such as the assignment operator = and the equality relation ==, do not work for them.

  2. Note that the use of the equal sign in a declaration such as:

    char happyString[12] = "YahBaDaBaDa";

    is an initialization statement and not an assignment.

  3. If a and b have been declared as arrays (whether or not they are cstrings) and if b has been given values, one cannot simply assign those values to a by an assignment statement such as:

    a = b; // illegal because the operator = is not defined for arrays

    For exactly the same reason, the second statement below is also illegal

    char happyString[12];
    happyString = "YahBaDaBaDa";       // illegal, the operator = is not defined for arrays

  4. Fortunately to assign values to cstrings can be accomplished using the predefined function called strcpy (which stands for string copy). An example of its usage is:

    char happyString[12];
    strcpy(happyString,"YahBaDaBaDa");

    The cstring happyString now contains the 11 characters "YahBaDaBaDa" plus an ending null character.

  5. The biggest problem with the function strcpy is that most C++ compiler does not check to see if its cstring argument has a declared size large enough to contain the resulting string plus the ending null character. If the cstring's size is not large enough, then strcpy can dangerously alter unintended memory spaces beyond the cstring.

  6. The equality operator == cannot be used to determine if two arrays are equal or not. For the same reason it cannot be used to determine the equality of two cstrings either .

  7. Instead, a Boolean predefined function strcmp (string comparison) can be used to compare two cstrings to check for equality.

  8. The following example illustrates how the function strcmp can be used:

    if (strcmp(cstring1, cstring2))
       cout << "The strings are not the same.";
    else
       cout << "The strings are the same.";

  9. The strcmp compares the characters in cstring1 with those in cstring2 a character at a time. It returns a negative value, a positive value or zero depending on whether cstring1 is less than, greater than, or equal to cstring2. In a Boolean expression, the returned negative or positive values will be evaluated to true and the the zero will be converted to false. Therefore the above code is indeed correct.

  10. According to ANSI C++ Standard, the functions strcpy and strcmp are described in the header file <cstring> and so it must be included with the preprocessor directive:

    #include <cstring>