views:

94

answers:

5

Hey Guys,

in C++ I want to initialize a double matrix (2-dimensional double array) like I would normally do without pointers like so:

    double data[4][4] = {
    1.0,0,0,
    0,1,0,0,
    0,0,1,0,
    0,0,0,1
};

However, since I want to return and pass it to functions, I need it as a double** pointer. So, basically I need to initialize data in a nice way (as above), but then afterwards I need to save the pointer to the 2d-array without losing the data when the function exits.

Any help on this? :-)

+1  A: 

Initialize temporary variable in this way and then copy it to the dynamically allocated memory.

Kirill V. Lyadvinsky
+2  A: 

double (*)[4] is very different from double **

Just sketch the layout of your doubles in the memory for both and you should understand why you can't use them interchangeably.

Didier Trosset
since I don't know or understand "double (*)[4]", I can't sketch it. What does it mean?
Felix
@Felix: It means "pointer to length-4 array of double".
Oli Charlesworth
+3  A: 

Unless you are particular about pointers, I would prefer a reference here

void init( double (&r)[4][4]){
    // do assignment
    r[0][0] = 1;
}

int main(){
    double data[4][4] = { 
        1.0,0,0, 
        0,1,0,0, 
        0,0,1,0, 
        0,0,0,1 
    }; 

    init(data);
}

By the way, if you pass it to a function in this manner, you would be "assigning" rather than "initializing".

Chubsdad
I think this answer is getting warmer. It might be the one I'm looking for!
Felix
By replacing "init" with a copy function, this models my problem elegantly. Thanks!
Felix
+2  A: 

Are all your matrices 4x4? Then I would simply define a class with a double[4][4] member and pass objects of that class around:

class Matrix
{
    double m[4][4];
    // ...
};

void function(const Matrix& matrix)
{
    // ...
}

If you need matrices of various dimensions, but they are known at compile time, use a template:

template <size_t n>
class Matrix
{
    double m[n][n];
    // ...
};

template <size_t n>
void function(const Matrix<n,n>& matrix)
{
    // ...
}

This saves you from dealing with array-to-pointer decay and makes the code more readable IMHO.

FredOverflow
A: 

First, declaration of the double dimensional array is not correct. It needs to be done as follows:

double data[4][4] = {  
        {1.0,0,0,0},  
        {0,1,0,0},  
        {0,0,1,0},  
        {0,0,0,1}  
    };

Second, for passing it in a function you can do it like

show(data);

In the function declaration, you need to give the argument as an array with giving all dimensions except the first. So the declaration would look like:

void show(double arr[][4])
{
   ...
   ...
}

This passes the array as a reference wihout you needing to use a pointer.

Hope this helped.

Mayank