Click here to Skip to main content
14,453,298 members

Introduction to dynamic two dimensional arrays in C++

Rate this:
1.71 (23 votes)
Please Sign up or sign in to vote.
1.71 (23 votes)
10 Dec 2007CPOL
An introduction to dynamic 2D arrays in C++.

Introduction

A dynamic array is an array data structure that can be resized and which allows elements to be added or removed.

There are many ways of creating two dimensional dynamic arrays in C++.

1. Pointer to pointer

First, we will allocate memory for an array which contains a set of pointers. Next, we will allocate memory for each array which is pointed by the pointers. The deallocation of memory is done in the reverse order of memory allocation.

int **dynamicArray = 0;

//memory allocated for elements of rows.


dynamicArray = new int *[ROWS] ;

//memory allocated for  elements of each column.


for( int i = 0 ; i < ROWS ; i++ )
dynamicArray[i] = new int[COLUMNS];

//free the allocated memory


for( int i = 0 ; i < ROWS ; i++ )
delete [] dynamicArray[i] ;
delete [] dynamicArray ;

The above code is for integer values. We can use the template to operate with generic types. In the below example, for the memory allocation, the AllocateDynamicArray function templates are used, and to free the memory, FreeDynamicArray is used.

template <typename T> 
T **AllocateDynamicArray( int nRows, int nCols)
{
      T **dynamicArray;

      dynamicArray = new T*[nRows];
      for( int i = 0 ; i < nRows ; i++ )
      dynamicArray[i] = new T [nCols];

      return dynamicArray;
}

template <typename T>
void FreeDynamicArray(T** dArray)
{
      delete [] *dArray;
      delete [] dArray;
}

int main()
{
      int **my2dArr = AllocateDynamicArray<int>(4,4);
      my2dArr[0][0]=5;
      my2dArr[2][2]=8;
      cout << my2dArr[0][0] << my2dArr[0][1] << endl;
      cout << my2dArr[1][1] <<  my2dArr[2][2]<< endl;
  
      FreeDynamicArray<int>(my2dArr);
      return 0;
}

2. Vector of vector

The above code can be done in one line of code by using a vector of vector, i.e., a vector containing an array of vectors.

vector<vector<T> > dynamicArray(ROWS, vector<T>(COLUMNS));

#include <span class="code-keyword"><vector></span>

using namespace std;

#define ROWS  4
#define COLUMNS  4

//vector<int > vec(5, 7); create a vector with 
//5 elements and each element will have the value 7.


vector<vector<int> > dynamicArray(ROWS, vector<int>(COLUMNS));

for(int i = 0;i < dynamicArray.size();++i)
{
      for(int j = 0;j < dynamicArray[i].size();++j)
      {
           dynamicArray[i][j] = i*j;
      }
}
 
for(int i = 0;i < dynamicArray.size();++i)
{           
     for(int j = 0;j < dynamicArray[i].size();++j)
     {
          cout << dynamicArray[i][j] << endl;
     }
}

3.Vector wrapper class

We have created a wrapper class DynamicArray with a vector<vector<T> > dArray data member. Then, we pass the number of rows and columns as arguments in the constructor.

template <typename T>
class DynamicArray
{
public:
    DynamicArray(){};

    DynamicArray(int rows, int cols): dArray(rows, vector<T>(cols)){}

    vector<T> & operator[](int i) 
    { 
      return dArray[i];
    }
    const vector<T> & operator[] (int i) const 
    { 
      return dArray[i];
    }
    void resize(int rows, int cols)//resize the two dimentional array .


    {
        dArray.resize(rows);
        for(int i = 0;i < rows;++i) dArray[i].resize(cols);
    }
private:
    vector<vector<T> > dArray;  
};

void Matrix(int x, int y)
{
    DynamicArray<int> my2dArr(x, y);
    my2dArr[0][0] = -1;
    my2dArr[0][1] = 5;
    cout << my2dArr[0][0] << endl;
    cout << my2dArr[0][1]  << endl;
}

int main(){

 Matrix(2,2);
 return 0;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Bibeka
Persistent
India India
No Biography provided

Comments and Discussions

 
QuestionFor Template allocation, memory leaks detected, So I used like below and no memory leaks now. Pin
Kranti Madineni15-Sep-17 19:14
MemberKranti Madineni15-Sep-17 19:14 
GeneralMy vote of 1 Pin
Yazeed Hamdan3-Mar-15 10:30
MemberYazeed Hamdan3-Mar-15 10:30 
General[My vote of 1] AllocateDynamicArray and FreeDynamicArray Pin
amtonyorourke26-Jan-11 18:39
Memberamtonyorourke26-Jan-11 18:39 
It 'leaks' like a sieve.

You've allocated memory but not deleted all of it correctly.

Here's why:
A array pointer in C/C++ is the address of the first member of the array.
In the FreeDynamicArray template you have the line

delete [] *dArray

The indirection operator * applied to dArray will return the address of the first member of dArray; ie a pointer the first 'row'

Calling delete on that pointer will delete the array that pointer represents - ie it will delete the values in the first row, but the rest of the rows remain allocated.

You need something like this:

template <typename T>;
void FreeDynamicArray(T** dArray, int size)
{
// size is the number of rows in the array
for(--size; size >= 0; size--)
delete [] dArray[size]; // delete each row

delete [] dArray; // delete the pointers to the rows
}

And you'll need the 'size' argument.
The sizeof operator can't return the size of dynamically allocated arrays

I see your template classes don't have a destructor at all.
They're going to need one, and it too needs to correctly delete allocated memory

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Article
Posted 6 Dec 2007

Stats

318.6K views
17 bookmarked