cpointersmultidimensional-arraycastingaddressing

Memory allocation when casting to a VLA type


I am puzzled by the memory allocation and accesses to a matrix of pointers in an application I am working in.

There is a matrix defined as:

typedef double (*foo)[n/m][m][m];

Which I understand to be a three-dimensional matrix storing pointers to doubles. The memory allocation for all dimensions is done automatically.

Nonetheless, the following appears:

foo bar = (foo) malloc(sizeof(double) * n * n);

What exactly is this cast doing?. Furthermore, why do we need to allocate memory for these doubles?. I would think the matrix only contains pointers, which would later be initialized with the memory addresses of doubles declared separately.

Finally, I am, also confused by the way this matrix is accessed during its initialization:

bar[i/m][j/m][i%m][j%m] = value;

Where i and j are smaller than N. Mainly, I would like to know what the fourth index is adressing.

Thank you so much in advance for your help!


Solution

  • This double (*foo)[n/m][m][m] creates 1 single pointer foo that will be used to point to 3 dimensional arrays containing values of type double, where the size of each of the 3 dimensions are n/m, m and m respectively, for a total of (n/m)*m*m = n*m double values in each 3 dimensional array.

    Note that you can use pointer's arithmetic over foo, so if foo points to one 3 dimensional array, then foo+1 will point to the next 3 dimensional array.

    In pointer notation you would do (*(foo+1))[0][0][0] to access the first double value of the second 3 dimensional array, and you can rewrite this using array notation as foo[1][0][0][0] to do the same thing. So now you can see that by iterating over foo you are iterating over the 4th dimension of a 4 dimensional array.

    From the code we see that it allocated n*n double values for this 4 dimensional array. So, as we don't know the size of the forth dimension, we could say that the dimensions of the array are something like [x][n/m][m][m] where x is the unknown size. But we do know that this 4 dimensional array will have n*n elements, so to find x we need to solve x*(n/m)*m*m = n*n, therefore x = n/m, and the dimensions are [n/m][n/m][m][m].