Week 6 Tutorial — Sample Solutions

  1. Assume in the tables below that the first column corresponds to address 0xdeadbee0, second to 0xdeadbee1, third to 0xdeadbee2 etc

    1. struct s1:

      address 0 1 2 3 4 5 6 7 8 9 a b c d e f 0 1 2 3
      s1 c ? ? ? i d ? ? ? j e ? ? ?

      • sizeof(s1) = 20
      • each of the chars requires 3 padding bytes (indicated by '?' in the table), so 9 bytes are used for padding
      • next available address is 0xdeadbef4

    2. struct s2:

      address 0 1 2 3 4 5 6 7 8 9 a b
      s2 i j c d e ?

      • sizeof(s2) = 12
      • there is just 1 padding byte
      • next available address is 0xdeadbeec
  2. A data structure to represent a member of a club:

    struct member {
    	char *name;
    	int phone;
    	struct address addr;
    	};
    
    struct address {
    	int house;
    	char *street;
    	char *city;
    };
    

    1. In the answers below, wherever we say 'a pointer to a variable of type T', we could equally well say 'the address of a memory location containing a value of type T'.

      Given the definitions:

      int x;
      int *p;
      int **q;
      

      then:

      x has type int (i.e. an integer value, most likely signed, 32-bits)
      *x is an error; it is invalid to dereference a non-pointer value
      &x has type int * (i.e. a pointer to an integer variable)
      p has type int * (i.e. a pointer to an integer variable)
      *p has type int (i.e. an integer value)
      &p has type int ** (i.e. a pointer to a pointer to an integer variable)
      q has type int ** (i.e. a pointer to a pointer to an integer variable)
      *q has type int * (i.e. a pointer to an integer variable)
      &q has type int *** (i.e. a pointer to a pointer to a pointer to an integer variable)

      • The term &x gives the address of x.
      • Dereferencing &x using the * operator says:
        • "give me the value of the thing being pointed to"
      • The thing being pointed to is x.
      • So, this expression gives you the value of x, which you can get simply via the expression x of course.

      So:
      *&x == x

    2. Given the following definition:

      int data[12] = {5, 3, 6, 2, 7, 4, 9, 1, 8};
      

      and assuming that &data[0] == 0x10000, then:

      data + 4 == 0x10010
      *data + 4 == data[0] + 4 == 5 + 4 == 9
      *(data + 4) == data[4] == 7
      data[4] == 7
      *(data + *(data + 3)) == *(data + data[3]) == *(data + 2) == data[2] == 6
      data[data[2]] == data[6] == 9

  3. per1.name == "Jack"
    per1.age == 20
    per1.gender == 'M'
    per1.birthday == "02-02-1990"
    per2.name == "Jill"
    per2.age == 19
    per2.gender == 'F'
    per2.birthday == "07-06-1990"