Home > Uncategorized > 2D Dynamic Array Template

2D Dynamic Array Template

</pre>
#include <iostream>
#include <string>

using namespace std;

// Initilization
template<class T>
void Init2DArray(T** &p, int rows, int cols)
{
    for (int x=0; x<rows; ++x)
    {
        for (int y=0; y<cols; ++y)
        {
            p[x][y] = T();
        }
    }
}

//Template
template<class T>
void Create2DArray(T** &p, int rows, int cols)
{
    p = new T* [rows];
    for (int i=0; i<rows; ++i)
    {
       p[i] = new T[cols];
    }
    Init2DArray(p, rows, cols);
}

template<class T>
void Delete2DArray(T** &p, int rows)
{

    for (int i=0; i<rows; ++i)
    {
       delete[] p[i];
    }

    delete[] p;
    p = 0;
}

template<class T>
void Show2DArray(T** &p, int rows, int cols, string arrayName = "p")
{
    for (int x=0; x<rows; ++x)
    {
       for (int y=0; y<cols; ++y)
       {
          cout << arrayName << "[" << x << "][" << y << "] = " << p[x][y] << " ";
       }
       cout << endl;
    }
}

int main(void)
{
    int **pInt;
    char **pChar;
    float **pFloat;
    int rows = 10;
    int cols = 5;
    Create2DArray(pInt, rows, cols);
    pInt[2][3] = 6;
    pInt[8][4] = 32;
    Show2DArray(pInt, rows, cols, "pInt");
    Delete2DArray(pInt, rows);

    Create2DArray(pChar, rows, cols);
    Show2DArray(pChar, rows, cols, "pChar");
    Delete2DArray(pChar, rows);

    Create2DArray(pFloat, rows, cols);
    Show2DArray(pFloat, rows, cols, "pFloat");
    Delete2DArray(pFloat, rows);

    system("pause");
    return 0;
}
<pre>
Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: