Wednesday, November 2, 2011

Three-Dimensional Array in C programming language

We aren’t going to show a programming example that uses a three-dimensional array. This is because, in practice, one rarely uses this array. However, an example of initializing a three-dimensional array will consolidate your understanding of subscripts:

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

A three-dimensional array can be thought of as an array of arrays of arrays. The outer array has three elements, each of which is a two-dimensional array of four one-dimensional arrays, each of which contains two integers. In other words, a one-dimensional array of two elements is constructed first. Then four such one-dimensional arrays are placed one below the other to give a two-dimensional array containing four rows. Then, three such two-dimensional arrays are placed one behind the other to yield a three-dimensional array containing three 2-dimensional arrays. In the array declaration note how the commas have been given. Figure  would possibly help you in visualising the situation better



Again remember that the arrangement shown above is only conceptually true. In memory the same array elements are stored linearly as shown in below Figure


How would you refer to the array element 1 in the above array? The first subscript should be [2], since the element is in third two-dimensional array; the second subscript should be [3] since the element is in fourth row of the two-dimensional array; and the third subscript should be [1] since the element is in second position in the one-dimensional array. We can therefore say that the element 1 can be referred as arr[2][3][1]. It may be noted here that the counting of array elements even for a 3-D array begins with zero. Can we not refer to this element using pointer notation? Of course, yes. For example, the following two expressions refer to the same element in the 3-D array:
 
arr[2][3][1] 
*( *( *( arr + 2 ) + 3 ) + 1 )

No comments:

Post a Comment