Introduction to Multidimensional Arrays - MyTechiest

Introduction to Multidimensional Arrays

In this blog, we will move towards the advanced concepts of arrays, i.e, multidimensional arrays. A two–dimensional array is the simplest form of a multidimensional array. We can see a two–dimensional array as an array of the one-dimensional array for easier understanding.


Initialization of two-dimensional array#

In C++, arrays can be declared as static and dynamic. A generic definition of initialization is given below:

Static two-dimensional array declaration:

data_type arr[x][y];

Dynamic two-dimensional array declaration:

datatype ** arr = new datatype *[rowSize];
for(int i=0; i<rowSize; i++)
   arr[i] = new datatype[colSize];

Data types could be int, float, double and char.

Consider the example below:

#include <iostream>
using namespace std;

int main() {
  const int row = 2, col = 2;

  // static array initialization
  int staticArr[row][col] = { {1, 2}, {3, 4}};
  
  cout << "Static two-dimensional array: ";
  for(int i=0; i<row; i++)
    for(int j=0; j<col; j++)
      cout << staticArr[i][j] << " ";     // printing static array

  cout << endl;
  
  // dynamic array initialization
  int ** dynamicArr = new int *[row];
  
  for(int i=0; i<row; i++)
    dynamicArr[i] = new int[col];
   
  int k=0;
  for(int i=0; i<row; i++)
    for(int j=0; j<col; j++)
      dynamicArr[i][j] = ++k;   // assgining values 
  
  cout << "Dynamic two-dimensional array: ";
  for(int i=0; i<row; i++)
    for(int j=0; j<col; j++)
      cout << dynamicArr[i][j] << " ";  
  
  cout << endl;
  // freeing memory
  for( int j = 0 ; j < row ; j++ ){
     delete [] dynamicArr[j];
  }
  delete [] dynamicArr;
}

Array indexing 

Each data element is assigned a numerical value that corresponds to the position of that item in the array. It is important to note that the value of the index is non-negative and always starts from [0][0]. So the first element of an array will be stored at Index [0][0] and the last one at Index [row-1][col-1].

An index makes it possible to access the contents of the array directly. Otherwise, we would have to traverse through the whole array to access a single element. Look at the figure below:


Changing elements in a 2-D array 

To change a static array element, we can simply access its index and change the value. For Example:

   int arr[2][2] = {{1,2},{3,4}};
   arr[1][1] = 10;

Now, the arr becomes {{1,2},{3,10}}

Note: We can change the elements of a static and dynamic array in the same way.

Post a Comment (0)
Previous Post Next Post