C++ array of arrays

There are two important ways to create array of arrays in C++ programming language. The first one is using two-dimensional array and the latter is using pointer and new operator. For the first way visit C++ 2D array.

In the second way by using pointer, new and delete operators, we can create array of arrays with better memory management because memory is allocated and released dynamically.

#include <iostream>
#include <conio.h>
using namespace std;

int main(){
   int fd=3;//number of elements in the upper array
   int sd=5;//number of elements in the lower array
  
   int **arr=(int**) new int*[sd]; //allocate upper level array
   for(int i=0;i<fd;i++)
     arr[i]=new int[sd];//allocate the lower level arrays
   //The first array contains three elements and each element
   //contains five elements.
   //assign 0 values to array elements
   for(int i=0;i<fd;i++){
        for(int j=0;j<sd;j++)
             arr[i][j]=0;
             }
   //loop through the array-print array
   for(int i=0;i<fd;i++){
        for(int j=0;j<sd;j++)
             cout<<arr[i][j]<<"\t";
        cout<<"\n";
        }
  
   //deallocate arrays
   for(int i=0;i<fd;i++)
        delete arr[i];
   delete []arr;
    
  
   getch();
   return 0;
}

Posted by: ly | post date: 01-27-2013 | Subject: C++ Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.