Thursday, October 20, 2011

Triple Pointer Operations in C++

Double pointer can be used to point to two dimensional matrix (pointer-to-pointer). If there are more than one matrices and it is required to keep track of these matrices then an additional extra pointer will be required. At his point triple-pointers can be used to point to list of two dimensional matrices.
We assume that you have got three different two-dimensional matrices as in the below picture:
Triple pointer with size of 3 and pointing to 3 different matrices:



#include <QCoreApplication>
#include <iostream>
using namespace std;

//function prototype
int** initializeMatrix(int** tempMatrix, int row, int column, int matrixCellValue);


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    int size = 3;
    int*** triplePointer;

    //Allocate memory for triplePointer
    triplePointer = new int**[size];

    int rowNum = 4;
    int columnNum = 3;
    int** newMatrix = 0;

    //Assign elements to cell values of each matrix
    for(int i=0; i<size; i++)
        triplePointer[i] = initializeMatrix(newMatrix,rowNum,columnNum,i);

    //Print elements of allocated matrices
    for(int num = 0; num<size; num++) {
        for(int i=0; i<rowNum; i++) {
            for(int j=0; j<columnNum; j++) {
                    cout<<triplePointer[num][i][j];
            }
            cout << "\n";
        }
        cout << "\n";
    }

    return a.exec();


}

/*
tempMatrix: matrix to allocate
row: number of rows of the matrix
column: number of columns of the matrix
matrixCellValue: value to assign to specified cell of matrix
 */
int** initializeMatrix(int** tempMatrix, int row, int column, int matrixCellValue)
{
    tempMatrix = new int*[row];
    for(int i=0; i<row; i++)
            tempMatrix[i] = new int[column];
    for(int i=0; i<row; i++)
            for(int j=0; j<column; j++)
                    tempMatrix[i][j] = matrixCellValue;

    return tempMatrix;
}


Sample c++ console application built with qt-creator on ubuntu and the console-output is 3 different 2x2 matrices displayed. Same output is produced when built with MSVS2008 on winXP.



1 comment: