Index Notation - C Implementation Details - Multidimensional Arrays

Multidimensional Arrays

Things become more interesting when we consider arrays with more than one index, for example, a two-dimensional table. We have three possibilities:

  • make the two-dimensional array one-dimensional by computing a single index from the two
  • consider a one-dimensional array where each element is another one-dimensional array, i.e. an array of arrays
  • use additional storage to hold the array of addresses of each row of the original array, and store the rows of the original array as separate one-dimensional arrays

In C, all three methods can be used. When the first method is used, the programmer decides how the elements of the array are laid out in the computer's memory, and provides the formulas to compute the location of each element. The second method is used when the number of elements in each row is the same and known at the time the program is written. The programmer declares the array to have, say, three columns by writing e.g. elementtype tablename;. One then refers to a particular element of the array by writing tablename. The compiler computes the total number of memory cells occupied by each row, uses the first index to find the address of the desired row, and then uses the second index to find the address of the desired element in the row. When the third method is used, the programmer declares the table to be an array of pointers, like in elementtype *tablename;. When the programmer subsequently specifies a particular element tablename, the compiler generates instructions to look up the address of the row specified by the first index, and use this address as the base when computing the address of the element specified by the second index.

Read more about this topic:  Index Notation, C Implementation Details