Converting multidimensional arrays to pointers in c++

Viewed 31405

I have a program that looks like the following:

double[4][4] startMatrix;
double[4][4] inverseMatrix;
initialize(startMatrix) //this puts the information I want in startMatrix

I now want to calculate the inverse of startMatrix and put it into inverseMatrix. I have a library function for this purpose whose prototype is the following:

void MatrixInversion(double** A, int order, double** B)

that takes the inverse of A and puts it in B. The problem is that I need to know how to convert the double[4][4] into a double** to give to the function. I've tried just doing it the "obvious way":

MatrixInversion((double**)startMatrix, 4, (double**)inverseMatrix))

but that doesn't seem to work. Is that actually the right way to do it?

8 Answers

There is a solution using the pointer to point by bobobobo

William Sherif (bobobobo) used the C version and I just want to show C++ version of bobobobo's answer.

int numRows = 16 ;
int numCols = 5 ;
int **a ;

a = new int*[ numRows* sizeof(int*) ];
for( int row = 0 ; row < numRows ; row++ )
{
    a[row] = new int[ numCols*sizeof(int) ];
}

The rest of code is the same with bobobobo's.

You can definitely do something like the code below, if you want.

template <typename T, int n>
class MatrixP
{
public:
    MatrixP operator()(T array[][n])
    {
        for (auto i = 0; i < n; ++i) {
            v_[i] = &array[i][0];
        }

        return *this;
    }

    operator T**()
    {
        return v_;
    }

private:
    T* v_[n] = {};
};

void foo(int** pp, int m, int n)
{
    for (auto i = 0; i < m; ++i) {
        for (auto j = 0; j < n; ++j) {
            std::cout << pp[i][j] << std::endl;
        }
    }
}

int main(int argc, char** argv)
{
    int array[2][2] = { { 1, 2 }, { 3, 4 } };
    auto pa = MatrixP<int, 2>()(array);

    foo(pa, 2, 2);
}
Related