Wednesday, October 12, 2011

Double Pointer Operations in C++

When initialized properly double pointers can be used as a 2 dimensional matrix. Sample qt-console application shows a way to allocate, initialize and deallocate a double pointer in C++.

Following diagrams help me to remember the subject of dynamically allocating multi-dimensional arrays in C++. 
Pointer-to-integer (simple integer array) declaration and representation: Can be considered as an array of integers.
int* ptrToInt;
pointer to integer
Pointer-to-pointer-to-integer (multi-dimensional matrix) declaration and representation: Can be considered as array of arrays of integers.
int** ptrToPtrToInt;
pointer to pointer to interger

#include <QCoreApplication>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    int** myRectRegion;

    int numRows = 4;
    int numCols = 3;

    //allocate double pointer
    myRectRegion = new int* [numRows];
    for(int i=0;i<numRows;i++)
            myRectRegion[i] = new int[numCols];


    //initialize double pointer
    for(int i=0; i<numRows; i++)
            for(int j=0;j<numCols;j++)
                    myRectRegion[i][j] = 1;


    //print double pointer elements
    for(int i=0; i<numRows; i++){
        for(int j=0; j<numCols; j++){
           cout << myRectRegion[i][j];
        }
        cout << "\n";
    }


    //free deallocate double pointer
    for(int i=0;i<numRows;i++)
            delete[] myRectRegion[i];
    delete[] myRectRegion;

    return a.exec();
}

When the application is run, a 4X3 matrix is displayed in the terminal window.

There is also a helpful tutorial about dynamic allocation of multi-dimensional arrays in C at : http://c-faq.com/~scs/cclass/int/sx9b.html

No comments:

Post a Comment