Assignment #6

Introductory C Programming

UW Experimental College

Assignment #6


Assignment #6
Assignment #5 Answers
Class Notes, Chapter 11
Class Notes, Chapters 12 and 13

Reading Assignment:

Class Notes, Chapters 10 and 11

Review Questions:

  1. If we say
    	int i = 5;
    	int *ip = &i;
    then what is ip? What is its value?
  2. If ip is a pointer to an integer, what does ip++ mean? What does
    	*ip++ = 0;
  3. How much memory does the call malloc(10) allocate? What if you want enough memory for 10 ints?
  4. The assignment in
    	char c;
    	int *ip = &c;		/* WRONG */
    is in error; you can't mix char pointers and int pointers like this. How, then, is is possible to write
    	char *cp = malloc(10);
    	int *ip = malloc(sizeof(int));
    without error on either line?


  1. Write a program to read lines and print only those containing a certain word. (For now, the word can be a constant string in the program.) The basic pattern (which I have to confess I have parroted exactly from K&R Sec. 4.1) is
    	while(there's another line)
    		if(line contains word)
    			print the line;
    Use the strstr function (mentioned in the notes) to look for the word. Be sure to include the line
    	#include <string.h>
    at the top of the source file where you call strstr.
  2. Rewrite the checkbook-balancing program from assignment 4 (exercise 6) to use the getwords function (from the notes) to make it easy to take the word ``check'' or ``deposit'', and the amount, from a single line.
  3. Rewrite the line-reversing function from assignment 4 (exercise 9) to use pointers.
  4. Rewrite the character-counting function from assignment 5 (exercise 3) to use pointers.
  5. Rewrite the string-concatenation program from assignment 5 (exercise 4) to call malloc to allocate a new piece of memory just big enough for the concatenated result. Don't forget to leave room for the \0!
  6. Rewrite the string-replacing function from assignment 5 (exercise 5) to use pointers.
  7. (harder) Write a program to read lines of text up to EOF, and then print them out in reverse order. You can use getline to read each line into a fixed-size array (as we have been doing all along), but you will have to call malloc and make a copy of each line before you read the next one. Also, you will have to use malloc and realloc to maintain the ``array'' of character pointers which holds all of the lines. (Your code will be similar to that in section 11.3 of the notes, p. 5)

    Extra credit: remove the restriction imposed by the fixed-size array into which each line is originally read; allow the program to accept arbitrarily many arbitrarily-long lines. (You'll have to replace getline with a dynamically-allocating line-getting function which calls malloc and realloc.)

This page by Steve Summit // Copyright 1995-9 // mail feedback