Thursday, July 3, 2008

Handling matrices in C++

Most of my programming work in C++ involves numerical computation based work. I have to deal with a lot of 2-dimensional matrices and the approach that I stuck to earlier was to use a pointer to a pointer.

double** matrix;

This allows for dynamic allocation of matrices. However I can't pass a pointer to a pointer and use const protection at the same time.
Say I have a function that just takes the 2-dimensional matrix and displays it. Now I want to protect the matrix from being inadvertently changed in the called function. So I want to declare the function as follows:

void function(const double** const matrix); // WRONG

The above can't be done :(

I am not even aware if a 2-dimensional array can be passed by reference in C++.

So this is what I am trying instead.

Say I have a 2-D matrix A as follows:
A = [1, 2,3]
[4,5,6]
[7,8,9]

then instead of defining this as :
A [3][3] = { {1,2,3}, {4,5,6}, {7,8,9}};

I define it as a single dimension array as follows :
A[9] = { 1,2,3,4,5,6,7,8,9} ;

That way one can easily pass the pointer as follows

void function(const double * const A );

-----------------------------------------------------------------

If you know a better solution please DO let me know.




No comments: