1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

All about Arrays in C/C++ - Part II

Discussion in 'C++' started by Mridula, Nov 14, 2009.

  1. Mridula

    Mridula New Member

    Joined:
    Mar 5, 2008
    Messages:
    316
    Likes Received:
    19
    Trophy Points:
    0
    Occupation:
    S/w proffessional
    Location:
    Bangalore

    Introduction



    This article talks about Multi-Dimensional Arrays in C/C++. About 1-Dimensional Array see All about Arrays in C/C++ - Part I

    Background



    Multi-Dimensional Arrays

    Multi-dimensional arrays are nothing but Array of Arrays.

    Characteristics

    All the characteristics that are mentioned for 1-Dimensional array hold good for multi-dimensional arrays too. Apart from that
    • Declaration of a multi-dimension array as a argument to a function, must include explicit size declarations in all of the subscript positions except for the first, which is an option.

    Memory Mapping

    In C/C++, memory mapping for multi-dimensional arrays, is done using Row Major ordering. It means, memory is allocated for successive elements by incrementing the rightmost index until it reaches the end of the current Row.

    2-Dimensional Arrays

    A 2-Dimensional Array is nothing but Array of 1-Dimensional Array and is represented with two subscripts as below:

    data_typeOfArray arrayName [firstDimension] [secondDimension]

    whereas firstDimension represents Rows and secondDimension as Columns.

    For Example:
    int array[2][3];

    Can be said as 2 Arrays of 1-Dimensional Array of size 3;

    2-Dimensional array can be imagined as a 2-D table made of elements of same data type as in below picture:

    [​IMG]

    Memory Mapping in 2-D Array

    For Example if we take int array[2][3];

    Here array will be considered as base address and successive address for the elements will be allocated at sizeOfElement*offset in Row Major Ordering. And here if we take the sizeOfElement as 1 then memory mapping for array[2][3] looks as below:

    array[0][0] --------> 0
    array[0][1] --------> 1
    array[0][2] --------> 2

    array[1][0] --------> 3
    array[1][1] --------> 4
    array[1][2] --------> 5

    Where 0,1,2 etc at right hand side are offsets

    Size of a 2-D Array

    Here size of the Array can be calculated as:
    firstDimension*secondDimension*sizeOfDataType

    For example:
    size of the int array[2][3] will be 2*3*4= 24 bytes

    Address of an Element

    Address of an Element at a given rowIndex and colIndex in an array[rowSize][colSize] can be calculated using the below formula:

    Element_Address = Base_Address + (col_size*(rowIndex) + (colIndex)) * Element_Size

    For Example:
    If we take the above array[2][3] with assumption of baseAddress as 0 and element size as 1, then address of element at indices array[0][1] can be found as:

    array[0][1] = 0 + (3*(0)+1)*1
    = 0 + (0+1)*1
    = 0 + 1
    = 1


    Initializing a 2-D Array

    As like in 1-D Arrays, 2-D Arrays can be initialized as below:

    int arry[2][3]={10,20,30,40,50,60}; or

    int array[2][3] = {{10,20,30}, {40,50,60}}

    And they are assigned with array indices as below:

    array[0][0]=10;
    array[0][1]=20;
    array[0][2]=30;
    array[1][0]=40;
    array[1][1]=50;
    array[1][2]=60;


    Like in 1-D array, if some of the indices in an interger 2-D array are not given initilizers, then by default they will be initilized with 0. Also if we assign 2-D Array with {}, it would initialize all it's elements with 0 value.

    2-D Array of characters

    Like in 1-D Arrays, 2-D Arrays of strings can be initilized in two ways as below:

    char array[3][4] = {
    'd','o','g'
    'c','a','t',
    'r','a','t'
    }


    or

    char array[3][4] = {"dog", "cat", "rat"};

    As said above for integer arrays, if initilizers are not given for some elements in character arrays, they will be initilized with NULL characters.

    Accessing elements in 2-D Arrays

    In the above mentioned array i.e. int array[2][3], we can access the 1st Rowth 0th column element as array[1][0] i.e. 40

    Dynamic Allocation of 2-D Arrays

    Suppose we want an int array[row][col]. where size of row and col are unknown at compile time. Then we can allocate the array dynamically and access it's elements with below steps:

    • The name array will be a pointer to a pointer to int.
    • Initialliy allocate memory of size x for pointers to int i.e. array of pointers
    • Then allocate memory of size y for each of these pointer
    • Access each of the element of array as array[j], where i>=0 and <x and j>=0 and <y.
      [*]Free the memory by deallocating for each of the pointers and then array of pointers itself.


    For Example:

    The code



    Code:
    #include<iostream.h>
    
    int main()
    {
      int row, col;
      int **array; //array name
      int i, j;
      
      cout<<"Enter the matrix size i.e. row and column"<<endl;
      cin>>row;
      cin>>col;
    
      //allocate memory of size row to pointer to int
      array = new int*[row];
    
      //allocate memory of size col to each of the pointer to int 
      for(i=0; i<row; ++i)
      {
        array[i] = new int[col];
      }
    
      cout<<endl;
    
      cout<<"Please eneter the values array["<<row<<"]["<<col<<"] :\n";
      
      for(i=0; i<row; ++i)
      {
        for(j=0; j<col; ++j)
        {
          cin>>array[i][j];
        }
      }
    
      cout<<endl;
    
      cout<<"Contents of array["<<row<<"]["<<col<<"] are :\n";
    
      for(i=0; i<row; ++i)
      {
        for(j=0; j<col; ++j)
        {
          cout<<array[i][j];
        }
        cout<<endl;
      }
    
      cout<<endl;
    
      //now for each pointer, free its array of ints
      for (i = 0; i < row; i++) 
      {
        delete [] array[i];
      }
       
      //now free the array of pointers
      delete [] array;
      
      return(0);
    }
    
    Output:
    ------------
    ./a.out
    Enter the matrix size i.e. row and column
    2
    3
    
    Please eneter the values array[2][3] :
    1
    2
    3
    4
    5
    6
    
    Contents of array[2][3] are :
    123
    456
    
    2-Dimensional array as an Argument to a function

    As said above, the size of the first dimension may be omitted, but the second dimension has to be mentioned in the argument.

    For Example:

    The code



    Code:
    #include<iostream.h>
    
    double sum(double array[][3], int size) 
    {
      double temp = 0.0;
      
      for(int i = 0 ; i < size ; i++)
      {
        for(int j = 0 ; j < 3 ; j++)        
        {
          temp += array[i][j];
        }
      }
      return temp;
    }
    
    int main() {
      double array[2][3] = {
                             { 1.0,  2.0,  3.0},
                             { 5.0,  6.0,  7.0}
                           };
    
      cout << "Sum of all the elements in array[2][3] is: "<< sum(array, sizeof array/sizeof array[0])<< endl;
      return 0;
    }
    
    Output:
    ----------
    Sum of all the elements in array[2][3] is: 24
    
    Easy way of reading a 2-D Array

    Imagine a 2-D array as shown in below example picture and then put the elements at the respective indices in the picture. This helps to read/recognise any element of the array at a given indcies.

    [​IMG]

    3-Dimensional Arrays

    Multi Dimensional Arrays are not limited to 2-D alone. They can be of as many indices as needed. But developer must be careful here, as the memory that consume increases with proportional to the dimension.

    A 3-Dimensional Array can be said as Array of 2-Dimensional Arrays and is represented with three subscripts as below:

    data_typeOfArray arrayName [firstDimension] [secondDimension] [thirdDimension]
    whereas firstDiemnsion is also called as depthSize here.

    For Example:

    int arry[2][3][4]; can be called as
    2 Arrays of 2-Dimensional Arrays of size 3X4 !!

    Memory Mapping in 3-D Array

    If we take int array[2][3][4];

    And array will be considered as base address and successive address for the elements will be allocated at sizeOfElement*offset in Row Major Ordering as below:

    array[0][0][0] --------> 0
    array[0][0][1] --------> 1
    array[0][0][2] --------> 2
    array[0][0][3] --------> 3

    array[0][1][0] --------> 4
    .
    .
    .

    array[0][2][0] --------> 8
    .
    .
    .
    array[1][0][0] --------> 12
    .
    .
    .
    array[1][1][0] --------> 16
    .
    .
    .
    array[1][2][0] --------> 20
    array[1][2][1] --------> 21
    array[1][2][2] --------> 22
    array[1][2][3] --------> 23

    Where 0,1,2 etc at right hand side are offsets

    Size of a 3-D Array

    Here size of the Array can be calculated as
    firstDimension*secondDimension*thirdDimension*sizeOfDataType

    For example the size of the below array will be:
    int array[2][3][4]

    2*3*4*4 = 96 bytes


    Address of an Element

    Address of an Element at a given depthIndex, rowIndex and colIndex in an array[depthSize][rowSize][colSize] can be calculated using the below formula:

    Element Address = Base Address + ((depthIndex*colSize+colIndex) * rowSize + rowIndex) * Element_Size

    If we take the above array[2][3][4] with assumption of baseAddress as 0 and element size as 1, then address of an element at indices array[1][2][3] can be found as:

    array[1][2][3] = 0 + ((1*4+3)*3+2)*1
    = 0 + ((4+3)*3+2)1
    = 0 + ((7)*3+2)1
    = 0 + 23


    Easy way of Reading a 3-D Array

    Elements in a 3-D array also can easily be read/recognised by imagining the picture of the Array as below:

    [​IMG]
     
    bouzigue likes this.
  2. talk2mohdsaif

    talk2mohdsaif New Member

    Joined:
    Mar 8, 2009
    Messages:
    21
    Likes Received:
    0
    Trophy Points:
    0
    Location:
    Hamirpur(hp)
    good artical......
    thnx...........
     
  3. rasd123

    rasd123 Banned

    Joined:
    Nov 4, 2009
    Messages:
    40
    Likes Received:
    0
    Trophy Points:
    0
    I like this's, cool!
     
  4. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,276
    Likes Received:
    364
    Trophy Points:
    83
  5. technica

    technica New Member

    Joined:
    Dec 15, 2007
    Messages:
    107
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    well written. Such an article with examples, figures and code examples always help people to understand the concept better. Thanks for writing and sharing.
     
  6. rasd123

    rasd123 Banned

    Joined:
    Nov 4, 2009
    Messages:
    40
    Likes Received:
    0
    Trophy Points:
    0
    Right on, write on about whatever you feel best.
     

Share This Page