c++boostboost-multi-array

Boost multiarray 3D


I am using a boost mutli array for 2D as follows,

typedef boost::multi_array<double, 2> array_type;
    typedef array_type::index index;
    // initialize array
    array_type U(boost::extents[N][3]);
    for(index i = 0; i != N; ++i) {
        for(index j = 0; j != 3; ++j){
            U[i][j] = 0;
        }
    }

    double * pU = U.data();
    double (*arrayU)[3] = (double (*)[3])pU;

Now I am trying to implement it but for 3D, so far I have written the following,

typedef boost::multi_array<double, 3> array_type;
    typedef array_type::index index;
    // initialize array
    array_type U(boost::extents[M][N][4]);
    for(index i = 0; i != M; ++i) {
        for(index j = 0; j != N; ++j){
            for(index k = 0; k != 4; ++k){
            U[i][j][k] = 0;
            }
        }
    }

But the following part is still confusing for me, can you please tell me how to do it and explain it a little bit?

    double * pU = U.data();
    double (*arrayU)[3] = (double (*)[3])pU;

Solution

  • multi_array<T>.data() returns a pointer to the beginning of the contiguous block, then cast the pointer to a pointer of the array of 3 doubles which is an element of array of arrays. Take a look at this link: A pointer to 2d array
    EDIT:
    It's the same for 3D array, for example, you write this for 3D array:

    double * pU = U.data();
    double (*arrayU)[N][4] = (double (*)[N][4])pU;
    

    You have declared arrayU to be a pointer to a N * 4 matrix of double, that is, it points to an array of N arrays of 4 doubles. Given this, arrayU[0] is an array of N arrays of 4 doubles. However, since it is an array, it is automatically converted to a pointer to the first element of the array.