How to define multi-dimensional arrays in C/C++?


Array is a collection of same type of elements at contiguous memory location. The lowest address corresponds to the first element while highest corresponds to last element. Array index starts with zero(0) and ends with the size of array minus one(array size - 1). Array size must be integer greater than zero.

Let us see an example,

If array size = 10
First index of array = 0
Last index of array = array size - 1 = 10-1 = 9

Multi-dimensional arrays are arrays of array. The data is stored in tabular form in row major order.

Here is the syntax of multi-dimensional arrays in C language,

type array_name[array_size1][array_size2].......[array_sizeN];

Here,

  • array_name − Any name given to an array.

  • array_size − Size of array.

The following is how you can initialize a multi-dimensional array

type array_name[array_size1][array_size2].......[array_sizeN]; = { {elements} , {elements} , ... {elements} }

Here is an example of multi-dimensional array in C language,

Example

 Live Demo

#include <stdio.h>

int main () {
   int arr[2][3] = { {5,2,3}, {28,8,30}};
   int i, j;

   for ( i = 0; i < 2; i++ ) {
      for ( j = 0; j < 3; j++ )
      printf("arr[%d][%d] = %d\n", i, j, arr[i][j] );
   }
   return 0;
}

Output

Here is the output

arr[0][0] = 5
arr[0][1] = 2
arr[0][2] = 3
arr[1][0] = 28
arr[1][1] = 8
arr[1][2] = 30

Updated on: 25-Jun-2020

175 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements