Felix Felix - 1 month ago 11
C++ Question

C++ multi-dimensional array initialization

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

Answer

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".