Search code examples
c++multidimensional-arrayinitialization-list

How does initialization of two-dimensional arrays work?


came across the code shown below in a small C++ example:

int (*arr1)[ARRAY_SIZE];
int (*arr2)[ARRAY_SIZE];
int (*arr3)[ARRAY_SIZE];

then in the constructor of the class:

ParallelMultiply::ParallelMultiply(int mat1[ARRAY_SIZE][ARRAY_SIZE],

                   int mat2[ARRAY_SIZE][ARRAY_SIZE], 

                   int result_mat[ARRAY_SIZE][ARRAY_SIZE]):arr1(mat1), 

                   arr2(mat2), 

                   arr3(result_mat)
{

}

here, ParallelMultiply is the class, mat1, mat2, result_mat are 2-D arrays, and ARRAY_SIZE is the defined array length. But How can arr1, arr2 and arr3 can be initialized with two dimensional arrays?? Please explain.

Thank you!!


Solution

  • You may be familiar with the way an array can decay to a pointer and then that pointer can be used like an array (as long as its actual extent is known).

    When this sort of thing is done to a multidimensional array, you get a pointer to array with one less array bound. Then that pointer can be used like the multidimensional array.

    So arr1[i][j] and mat1[i][j] are the same int and have the same address.

    Note that since the class is copying only pointers to the 2D arrays, the user needs to make sure the lifetime of those array arguments is long enough. And any modifications made through the class will happen to the original arrays.