CS2112: Exercises + Answers from $14 Identifiers: Static and Dynamic Semantics

* When multiplication took longer than a memory access, a common implementation of multi-dimensional arrays was to use Iliffe vectors i.e. an array is a vector of pointers to vectors of pointers to... to vectors holding the actual elements. e.g. a 2-D array of integers is a vector of pointers to vectors of integers. During an access, the first index selects a pointer from the initial array, and the second index selects an integer from the vector pointed at.
This technique makes array slicing asymmetrical, as we can slice via the one index but not via the others. As the vectors of values are independent, they can in principle, have different sizes and bounds from each other.
In many languages it is possible for the user to explicitly write code to use Iliffe vectors. Using C, declare and access a 2-dimensional array using this technique. You will also need to ensure that the vectors of values exist and initialise the vector of pointers. Try obtaining the space for the values in two ways: using malloc, and using another local variable of suitable size.

#include <stdlib.h>
int main(void)
{
  int (*a[20])[10];	/* an array of 20 pointers to an array of 10 ints */
  int i, j;

  for (i=0; i<20; i++)
  {
    a[i]= malloc(10*sizeof(int));
    for (j=0; j<10; j++)
      (*a[i])[j]= i*j;
  }
  return 0;
}

I tested it by adding:

  int b[20][10];

  a[i]= b[i];

instead of a[i]= malloc(10*sizeof(int));
although it gives a type warning

  for (i=0; i<20; i++)
  {
    for (j=0; j<10; j++)
      printf("%d ", b[i][j]);
    printf("\n");
  }

and I got the output I expected.

I am rather disappointed that I couldn't write "a[i][j]" - this got a warning and did the wrong thing at run-time.