Introduction
Just as with a two-dimensional array, you can define three-dimensional arrays and processing in a similar way. Each three-dimensional array is taken as an array of two-dimensional arrays.
Program
#includemain() { int a[2][3][4]; \\ A int b[3][4]; \\ B int c[4]; \\ C int cnt=0; for(int i=0;i<2;i++) for(int j=0;j<3;j++) for(int k=0;k<4;k++) { a[i][j][k] = cnt; cnt; } } void print_onedim(int a[]) \\ D { for(int i=0;i<4;i++) printf("%d ",a[i]); } void print_twodim(int a[][4]) \\ E { for(int j=0;j<3;j++) print_onedim(a[j]); printf("\n"); } void print_threedim(int a[][3][4]) \\ F { printf("Each two dimension matrix\n"); for(int j=0;j<2;j++) print_twodim(a[j]);; }
Explanation
-
The three-dimensional array consists of two arrays of the size 3 × 4. Each is referred to as a[0] a[1]. Thus a[0] consists of 12 elements and a[1] also consists of 12 elements.
-
Each two-dimensional array is taken as three arrays of the size 4.
-
The function print_onedim prints a single-dimensional array.
-
The function print_twodim prints a two-dimensional array and it calls the function for printing a single-dimensional value.
-
The function print_threedim prints a three-dimensional array and calls the function for printing a three-dimensional value.
-
Dimension two, which is closer to the array name, is called the outermost dimension, and dimension four, which is far from the array name declaration, is called the innermost dimension.
-
When you pass an array to the function, you have to specify the inner dimension. For example, to print two_dim you have to specify the inner dimension, i.e. 4, and for printthree_dim you have to pass 3 and 4 as inner dimensions.
-
When you pass a single-dimension array, you need not pass a dimension because the function knows what the best address of the array is.
-
In a case of a two-dimensional array, we have to pass the inner dimension because only then does the function know the base address of each array. For example, if the declaration is
int a[3][4]
it is considered as three arrays of the size 4. So the base address of a[0] is a itself. The base address of a[1] is a+8 because the first row has 4 elements of size 2 bytes each; thus we can get the base address of a[1]. Similarly, the base address of a[2] is a+16. Thus, to calculate the base address, you should know the inner dimension, 4.
Points to Remember
-
You can declare a multi-dimensional array and access it in a similar way to accessing a two-dimensional array.
-
While passing an array to the function, you have to specify the inner dimension to facilitate calculations of the base addresses.
No comments:
Post a Comment