Working with C Strings

Recall that there is no String datatype in C. Strings in C are just arrays of, or pointers to, char. The last character in a string is the null character '\0' (integer value, or ASCII code, 0).

In yout class directory, create another directory called Strings. In the directory Strings, write code for the exercises below.

  1. Write a function length that takes as argument a character string and returns the length the string - this is the number of characters in the string, not including the terminating null character '\0'.
        int length(char * s)  /* int length(char s[ ]) */
        {
            int i, count = __________;
    
            /* Insert code here */
    
            return count;
        }
    
        int main()
        {
            int n1, n2, n3, n4;
    
            n1 = length("abc");	// n1 should be 3
            n2 = length("abc\0");	// n2 should be 3
            n3 = length("abc\0\0");	// n3 should be 3
            n4 = length("abc\\0");	// n4 should be 5
    
            printf("[%d, %d, %d, %d]\n", n1, n2, n3, n4);
        }
    

  2. Learn about the C function strlen using the Unix manual pages. To do so, type in
    			man strlen
    
    at the shell prompt. A series of functions that operate on strings will be listed for you. Identify the strlen function and learn what it does, then rewrite the program from exercise 1 using strlen instead of length.

  3. Consider the following piece of C code:
        char sa[4] = {'o', 'n', 'e', '0'};
        char sb[4] = {'t', 'w', 'o', '0'};
        char sc[] = "three";
    
        int main()
        {
            printf("String sa is [%s]\n", sa);
            printf("String sb is [%s]\n", sb);
            printf("String sc is [%s]\n", sc);
        }
    
    (a) Compile and run the program. The values printed for sa and sb are incorrect. Why? Without altering the code given, add new lines of code that would fix the value of sa to one and the value of sb to two.

    (b) Declare an array of three pointers, and set these pointers to point to sa, sb and sc. Expand the code above to print out the values of the three pointers (should be one, two and three).

    (c) Write code that appends the character '-' and the string sa at the end sb (use strcat) so that the value of sb becomes two-one. Use the three pointers declared in (b) as arguments to strcat. Print out these pointers again. The values should be

         one
         two-one
         three
    
    You may need to change the size of the strings sa, sb and sc to make this happen.