Software & Finance





C++ - Dynamic 3D Arrays using Quadruple Pointer Template Functions





Many programmers are hesitating to use the pointers because of complexity and memory management. Nevertheless it is a powerful feature in C++ and gives more control to the programmers.

In this sample code, I have explained how to create and delete a 3-Dimensional dynamic array using a temple functions Create3D_Array and Delete3D_Array


Source Code


#include "stdafx.h"

#include <iostream>

 

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

 

template<class Type>

int Create3D_Array(Type ****pResult, int x, int y, int z)

{

    Type ***p = new Type **[x];

    for(int i = 0; i < x; i++)

    {

        p[i] = new Type *[y];

        for(int j = 0; j < y; j++)

            p[i][j] = new Type[z];

    }

    *pResult = p;

    return x * y * z;

}

 

template<class Type>

int Delete3D_Array(Type ****pResult, int x, int y, int z)

{

    Type ***p = *pResult;

    for(int i = 0; i < x; i++)

        for(int j = 0; j < y; j++)

            delete p[i][j];

 

    for(int i = 0; i < x; i++)

        delete p[i];

    delete p;

    return 0;

}

 

void TestFunc()

{

    int ***pInt = NULL;

    float ***pFloat = NULL;

    Create3D_Array(&pInt, 2, 4, 6);

    Create3D_Array(&pFloat, 2, 3, 5);

 

    int count = 0;

    for(int i = 0; i < 2; i++)

    {

        for(int j = 0; j < 3; j++)

            for(int k = 0; k < 5; k++)

                pFloat[i][j][k] = count += 3;

    }

 

    for(int i = 0; i < 2; i++)

    {

        for(int j = 0; j < 3; j++)

        {

            for(int k = 0; k < 5; k++)

            {

                char buf[512];

                sprintf(buf, "Array[%d][%d][%d] = %.2f\n", i, j, k, pFloat[i][j][k]);

                std::cout << buf;

            }

        }

    }

 

    Delete3D_Array(&pFloat, 2, 3, 5);

    Delete3D_Array(&pInt, 2, 4, 6);

}

Output


Array[0][0][0] = 3.00
Array[0][0][1] = 6.00
Array[0][0][2] = 9.00
Array[0][0][3] = 12.00
Array[0][0][4] = 15.00
Array[0][1][0] = 18.00
Array[0][1][1] = 21.00
Array[0][1][2] = 24.00
Array[0][1][3] = 27.00
Array[0][1][4] = 30.00
Array[0][2][0] = 33.00
Array[0][2][1] = 36.00
Array[0][2][2] = 39.00
Array[0][2][3] = 42.00
Array[0][2][4] = 45.00
Array[1][0][0] = 48.00
Array[1][0][1] = 51.00
Array[1][0][2] = 54.00
Array[1][0][3] = 57.00
Array[1][0][4] = 60.00
Array[1][1][0] = 63.00
Array[1][1][1] = 66.00
Array[1][1][2] = 69.00
Array[1][1][3] = 72.00
Array[1][1][4] = 75.00
Array[1][2][0] = 78.00
Array[1][2][1] = 81.00
Array[1][2][2] = 84.00
Array[1][2][3] = 87.00
Array[1][2][4] = 90.00