Menu

Class 5: Homework


You must print this sheet out and write/type answers on it!

  1. Answer given questions based on this code:
    #include <stdio.h>
    
    int N = 2;
    
    int main()
    {
      char fn[256];
      if (fscanf(stdin,"%s",fn) != 1)
      {
        fprintf(stderr,"No name read!\n");
        return 1;
      }
    
      FILE* fis = fopen(fn,"r");
      char *buff = (char*)malloc(N*sizeof(char));
      int i = 0;
      buff[i] = '\0';
    
      char next;
      while((next = fgetc(fis)) && next != EOF)
      {
        if (i == N-1)
        {
          N = 2*N;
          char* buffp = (char*)malloc(N*sizeof(char));
          strcpy(buffp,buff);
          free(buff);
          buff = buffp;
    
        }
        buff[i++] = next;
        buff[i] = '\0';
      }
    
      if (buff[i-1] = '\n') 
        --i;
      while(--i >= 0)
      {
        fprintf(stdout,"%c",buff[i]);
      }
      fprintf(stdout,"\n");
    
      return 0;
    }
    
    a) For each of the following, state whether the object is statically allocated, stack allocated, or heap allocated:
    1. fn
    2. N
    3. fn[2]
    4. buff[2]
    5. buffp
    6. stdout ← HINT: you should be able to reason this out based on what you know!

    b) What is the type of stdout? Hint: look at fprintf's prototype and you should be able to figure out what its type must be!

    
    	  
  2. Annotate the following code so that each * in the code is labelled as either pointer declaration, pointer dereference, or multiplication.
    int egcd(int u, int v, int *s, int *t)
    {
      if (v == 0)
      {
        *s = 1;
        *t = 0;
        return u;
      }
      int gp, sp, tp, q, r;
      q = u/v;
      r = u%v;
      gp = egcd(v,r,&sp,&tp);
      *s = tp;
      *t = sp - tp*q;
      return gp;
    }
    
  3. Explain why, in the code above, the recursive call egcd(v,r,&sp,&tp) has the &'s in front of sp and tp.
    
    
    
    
    
    
    	    
  4. Why is it that this code causes a program to crash
    char *name;
    scanf("%s",name);
    
    ... but this code doesn't:
    char name[20];
    scanf("%s",name);
    
    
    
    
    
    
  5. Fill in the blanks. To create an array A of 20 doubles:
    ________ A = ( ________ ) malloc( ______  * sizeof( _______ ));
    	    
    
    	  
  6. Fill in the blanks. To create an array B of 10 strings:
    ________ B = ( ________ ) malloc( ______  * sizeof( _______ ));
    	    
    
    	  
  7. Define a function div that takes to integers x and y and produces their quotient (x/y) and remainder (x % b). You should be able to call the function like this:
    int a,b,q,r;
    scanf("%i %i",&a,&b);
    div(a,b,&q,&r); ← after the call q is the quotient, r is the remainder.