Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 337
Felix Avatar asked Aug 24 '10 07:08

Felix


People also ask

How do you initialize a multidimensional array to 0?

A multidimensional array in C is nothing more than an array of arrays. Any object can be initialized to “zero” using an initializer of = { 0 } . For example: double two_dim_array[100][100] = { 0 };

Does C allow multidimensional arrays?

In C programming, you can create an array of arrays. These arrays are known as multidimensional arrays. For example, float x[3][4];


2 Answers

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

like image 187
Chubsdad Avatar answered Sep 19 '22 01:09

Chubsdad


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.

like image 44
fredoverflow Avatar answered Sep 22 '22 01:09

fredoverflow