Alex Rivera | Logout

C++ multi-dimensional array initialization

Asked 2010-08-24T07:14:06.123
9

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? :-)

Edit
Report

1 Answer

6

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.

answered 2010-08-24T08:13:58.520

Your Answer