MC logo

Pointers and Arrays (Answer)

  Practice Questions

  1. What is printed by the following code?
         #include <stdio.h>
         void f(int *aa, int *bb)
         {
              *bb = 8;
              aa[1] = bb[2];
              aa = bb;
         }
    
         main()
         {
              int a[5] = { 1, 2, 3, 4, 5 }, *b;
              b = a + 2;
              f(a,b);
              printf("%d %d %d %d %d\n", 
                       a[0], a[1], a[2], a[3], a[4]);
         }
    

    The program prints:

    1 5 8 4 5

    Keep in mind that the statement aa = bb; does not change any variable in main. Here is a diagram that shows the situation just before the execution of aa = bb;.
    _BL_ [Diagram: Array contains 1, 5, 8, 4, 5; aa ==> a[0], bb ==> a[2]. ]

  2. What is printed by the following code?
         #include <stdio.h>
         void g(int *aa, int *bb)
         {
              bb[2] = aa[-2];
              *aa++ = 17;
              *++aa = 10;
         }
    
         main()
         {
              int blap[7] = { 1, 2, 3, 4, 5, 6, 7 };
              int *c = blap + 3;
              g(c,blap);
              printf("%d %d %d %d %d %d %d\n", 
                       blap[0], blap[1], blap[2], blap[3], blap[4],
    		   blap[5], blap[6]);
         }
    

    The code prints:

    1 2 2 17 5 10 7

    Be sure to distinguish between the post-increment and the pre-increment. In the following diagram, the black parts refer to the situation just before g returns, and the red parts refer to the situation at the start of g.
    _BL_ [Diagram: Array as output; aa ==> blap[6], moved from blap[4]. ]

  3. a[i] is equivalent to each of the expressions.
    • First, a[i] is *(a + i) by definition.
    • Of course, *(a + i) is *(i + a), and hence i[a].
    • The & and * are inverse operations, so *&a[i] is just a[i]. In fact, *&x is x for any x (except a few cases we have not discussed where the expression is illegal).
    • By definition, (a+1)[i-1] is *((a+1) + (i-1)), which is *(a + i), hence a[i]. Another way to look at it is that (a+1)[i-1] starts one slot further down (at a+1 instead of a), and proceeds one slot less far (to [i-1] instead of [i]), hence ends up at the same place as a[i].
    • Finally, the above property of & and * reduces (*&i)[&*a] to (i)[a], which is a[i], as noted above.

  4. The expression (&m)[1] = m compiles and assigns the value of m into the location in memory immediately following m. Probably not a good idea. Since subscripting is not bounds-checked in C, the compiler does not notice that it is a bad idea. It compiles because subscript happily takes any pointer and any integer; &m is a pointer, and 1 is an integer.

<<Control Constructs Question Pointers and Strings>>