Answer to Quiz 10(b) Thu 1 Nov 2001

1. Consider the program below :

#include<stdio.h>
                                                  variables
void square ( int *p );                    -------------------------
                                             in main  |  in square
int main(void)                             =========================
{                              before        i        |
   int i = 5;                                +----+   |
   square(&i);                               |  5 |   |
   printf("%d",i);                           +----+   |
   return 0;                   during                 |
}                                            i        | p        n
                                             +----+   | +-----+  +----+
void square ( int *p )                       |  5 | <---|- &i |  | 25 |
{                                            +----+   | +-----+  +----+
   int n = *p * *p;            after                  |
   *p = n;                                   i        |
}                                            +----+   |
                                             | 25 |   |
                                             +----+   |

Make at the right of the program a diagram of all variables in main
and square.  

Illustrate what happens before, during, and after the
call of square(&i).

What does the program print?  25

2. Suppose we wish to count the number of occurrences 
   of a character in the input. 

   In main we read characters until EOF is found, 
   for each input character we call

   void charcnt ( int *input, char c );
   /* if *input == EOF, *input on return is the number of occurrences of c,
      otherwise, the counter is updated depending whether c == *input. */

Give a definition of charcnt.
Make sure charcnt ``remembers'' correctly.

   void charcnt ( int *input, char c )
   {
      static int cnt = 0;

      if (*input == EOF) *input = cnt;
      if (*input == c) cnt++;
   }