Week 4 Tutorial — Pointers, Strings, Arrays

  1. Consider the following array and pointer declarations:

    char p[] = "robert"
    char *q  = "robert"
    

    1. What is the output of each of the following print statements?

      printf("%s\n", p);
      printf("%s\n", q);
      printf("%c\n", *p);
      printf("%c\n", *q);
      printf("%c\n", p[0]);
      printf("%c\n", q[0]);
      printf("%c\n", *(p+1));
      printf("%c\n", (*p)+1);
      

    2. If we want to change the first letter to upper-case in both strings using:

      p[0] = 'R';
      *q = 'R';
      

      what will be the result?
    3. What will be the result of the following 'copy' instructions?

      p = q;
      

      q = p;
      

  2. If I declare:

    char r[5] = "junk";
    char s[2] = "a0";
    char t[3] = "b1";
    

    what will the following fragment output?

    printf("%s\n", r);
    printf("%s\n", s);
    printf("%s\n", t);
    

  3. Consider the declarations:

    char *days1[]   = {"monday", "tuesday", "wednesday"};
    char days2[][9] = {"monday", "tuesday", "wednesday"};
    

    1. There is a (potential) bug here: what is it?
    2. In the corrected code, what storage is allocated for these two declarations?
    3. If c is defined as a char, which of the following are legal:
      1. c = days1[0][0];
      2. c = days2[0][0];
      3. days1[0][0] = 'M';
      4. days2[0][0] = 'M';
      5. days1[0] = "MONDAY";
      6. days2[0] = "MONDAY";
  4. In the following table a number of arrays have been defined. Fill in the minimum index, maximum index, sizeof() each element and sizeof() the whole data structure in each case.

    Data structure Min. Max. sizeof() element sizeof() structure
    char str[50];        
    int counts[100];        
    double temps[31];        
    int m[20][50];        
    char *names[20];        
    char *argv[];        
  5. Suppose that the C declaration

    int A[4] = {1, 256, 65536, 16777216};
    

    results in A being allocated to memory based at address 0x800000.

    1. Sketch the memory map for array A using hexadecimal notation to represent the contents of each byte. Assume that the machine has a 4-byte word size.
    2. What is the address of A[3]?
    3. What is the value of the byte at address 0x800006?
    4. Which element of A has address 0x800008? What is the value of that element in hexadecimal notation?

  6. Write two different versions of the C standard library function to determine the length of a string, where the function has the interface:

    int strlen(char *str);
    

    The two versions of strlen() should differ as follows:
    1. iteration is controlled via an index variable, i.e. int
    2. iteration is accomplished via a pointer variable i.e. char *