C++ casting static two-dimensional double array to double**

c++, casting, double, pointers

Solution

You can't just cast the array. You are going to have to create something like this:

double m[3][4] = 
    {
        {2, 4, 5, 7},
        {4, 5, 1, 12},
        {9, 12, 13, -4}
    };

double *marray[3] = {m[0],m[1],m[2]};
calculate(marray,3);

Or you can use a loop:

const size_t n = 3;
double *marray[n];
for (size_t i=0; i!=n; ++i) {
    marray[i] = m[i];
}
calculate(marray,n);

Problem

I have such matrix in my program: ``` double m[3][4] = { {2, 4, 5, 7}, {4, 5, 1, 12}, {9, 12, 13, -4} }; ``` And I'd like to cast it to `double**` type. I've already tried simple `double** a = (double**)m;`, but it doesn't work (when I try to read any value, I get "Access violation reading location 0x00000000.", which means I'm trying to read from `NULL` adress. I found almost working solution: ``` double *b = &m[0][0]; double **c = &b; ``` It works when I read field `c[0][any]` But same NULL adress reading problem occurs, when I try to read value from field `c[1][0]`. What is the proper way to cast my `double m[3][4]` array to type `double**`? edit: You say that's impossible. So I'll change a problem a little bit. How can I pass two-dimensional double array as a parameter to a function? My function has prototype: ``` void calculate(double **matrix, int n); //where matrix size is always n by n+1 ``` And it's working fine with dynamically-allocated arrays. I doubt that only way to make it work is allocating new dynamical array and copy original static array one element by another...

Original source

Related problems