Multi dimensional arrays in C

Previous
Next

Multi dimensional arrays:

  • More than 2 dimensional arrays come under multi dimensional arrays.
  • To process the elements of n dimensions, we use n arrays with nested form
  • The memory representation as follows.
  • The elements of an array can be of any data type, including arrays! An array of arrays is called a multidimensional array.

The declaration form of Three-dimensional array is

Data_type     Array_name [size1][size2][size3];

For example,

Int [2][3][5];

In the above three dimensional matrix we can store 2*3*5 elements in the corresponding locations.

  • 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, 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.
#include<stdio.h>
int main()
{
	int a[2][2][2], i,j,k;
	
	printf("Locations :\n");
	for(i=0 ; i<2 ; i++)
		for(j=0 ; j<2 ; j++)
			for(k=0 ; k<2 ; k++)
				printf("a[%d][%d][%d] \n", i, j, k);
	return 0;	
}

We can represent the above array as follows:

  • When a function receives a single-subscripted array as an argument, the array brackets are empty in the function’s parameter list.
  • The first subscript of a multiple-subscripted array is not required either, but all subsequent subscripts are required.
  • The compiler uses these subscripts to determine the locations in memory of elements in multiple-subscripted arrays.
  • To pass one row of a double-subscripted array to a function that receives a single-subscripted array, simply pass the name of the array followed by the subscript (in square brackets) of that row
#include <stdio.h>
 void printSize (int x[][3][3]) 
{
    printf("size of x: %d\n", sizeof(x)); 
    return;
}
 int main()
{
    int i,j,k;
    int p[6][3][3];
    for(i=0;i<6;i++) 
	for(j=0;j<3;j++) 
	for(k=0;k<3;k++) 
	p[i][j][k] = i;
    printf("size of p: %d\n", sizeof(p)); 
    printSize(p);
    return 0;
}
Previous
Next

Add Comment

Courses Enquiry Form