Sams Teach Yourself C in 21 Days

(singke) #1
Working with Characters and Strings 247

10



  1. Write code that allocates space for an 80-character string and then inputs a string
    from the keyboard and stores it in the allocated space.

  2. Write a function that copies one array of characters into another. (Hint: Do this just
    like the programs you wrote on Day 9.)

  3. Write a function that accepts two strings. Count the number of characters in each,
    and return a pointer to the longer string.
    7.ON YOUR OWN:Write a function that accepts two strings. Use the malloc()
    function to allocate enough memory to hold the two strings after they have been
    concatenated (linked). Return a pointer to this new string.
    For example, if I pass “Hello”and“World!”, the function returns a pointer to
    “Hello World!”. Having the concatenated value be the third string is easiest. (You
    might be able to use your answers from exercises 5 and 6.)
    8.BUG BUSTER:Is anything wrong with the following?
    char a_string[10] = “This is a string”;
    9.BUG BUSTER:Is anything wrong with the following?
    char quote[100] = { “Smile, Friday is almost here!” };
    10.BUG BUSTER:Is anything wrong with the following?
    char
    string1;
    char *string2 = “Second”;
    string1 = string2;
    11.BUG BUSTER:Is anything wrong with the following?
    char string1[];
    char string2[] = “Second”;
    string1 = string2;
    12.ON YOUR OWN:Using the ASCII chart, write a program that prints a box on-
    screen using the double-line characters.


Today’s lesson dynamically allocated memory using the malloc()function.
When you dynamically allocate memory, you should release it back to the
computer system when you are done with it. You can put dynamically allo-
cated memory back by freeingit. Day 20 will cover freeing allocated mem-
ory.

Caution


17 448201x-CH10 8/13/02 11:17 AM Page 247

Free download pdf