Reliable Software Logo

C++ In Action

Exercises

Compare with solutions.


  1. Implement the function:
    void StrCpy (char* strDest, char* strSrc);
    that copies the source string up to and with the terminating null into the destination string. The destination string is assumed to have enough space (unfortunately, we can’t simply assert it). Use the "indexing the array" method rather than pointers to char.
  2. Implement the function
    int StrCmp (char* str1, char* str2);
    that lexicographically compares two strings. It returns zero when the strings are equal. Otherwise it returns a number greater than or less than zero if the first differing character in string 1 corresponds to, respectively, greater or smaller ASCII code than the corresponding character in string 2. The comparison stops when a null character is encountered in either string. If string 1 is longer, a positive number is returned; if string 2 is longer, a negative number is returned. Use the index implementation.
  3. Another of these old "optimizing" tricks is to run a loop backwards. Instead of incrementing the counter we decrement it until it becomes negative or reaches zero. (At some point every programmer gets bitten by this trick when the loop variable is of the unsigned type.)

    Find a bug and rewrite the function

    void StrNCpy (char* strDest, char* strSrc, size_t len)
    {
    	while (--len >= 0)
    	*strDest++ = *strSrc++;
    }
    where size_t is some unsigned integral type defined, for instance, in cstring. Get rid of the "optimizing" tricks introduced here by a human compiler.

NextNext: Pointers and Dynamic Memory Allocation