Cstring as Function Arguments

  1. A cstring variable is an array, so a cstring parameter to a function is simply an array parameter.

  2. As with any array parameter, whenever a function changes the value of a cstring parameter, it is safest to include an additional integer parameter giving the declared size of the cstring variable.

  3. If a function only uses the value in a cstring argument, but does not change that value, then there is no need to keep track of its declared or actual size. The null character can be used to detect the end of the cstring value.

  4. // Example to demonstrate some of the cstring functions
    // and the usage of cstring parameters in a function.
    #include <iostream>
    #include <cstring>
    using namespace std;

    void string_copy(char target[ ], const char source[ ], int target_size);
    //Precondition: target_size is the declared size of the string variable
    //target. The array source contains a string value terminated with '\0'.
    //Postcondition: The value of target has been set to the string value in
    //source, provided the declared size of target is large enough.
    //If target is not large enough to hold the entire string, a string equal
    //to as much of the value of source as will fit is stored in target.

    int main( )
    {
       char short_string[11];       //Can hold strings of up to 10 characters.
       string_copy(short_string, "Hello", 11);
       cout << short_string << "STRING ENDS HERE.\n";

       char long_string[ ] = "This is rather long.";
       string_copy(short_string, long_string, 11);
       cout << short_string << "STRING ENDS HERE.\n";
       return 0;
    }

    //Uses cstring:
    void string_copy(char target[ ], const char source[ ], int target_size)
    {
       int new_length = strlen(source);
       if (new_length > (target_size - 1))
          new_length = target_size - 1;       //That is all that will fit.
       for (int index = 0; index < new_length; index++)
          target[index] = source[index];
       target[index] = '\0';
    }

    The program output is:
    HelloSTRING ENDS HERE
    This is raSTRING ENDS HERE