#include <stdlib.h>
#include <stdio.h>
double * globalArray; /* working from a situation where the array is global, declared elsewhere */
int M, N, P; /*array dimensions not known until runtime */
double reduce();
double reduce()
{
/* Here I want to re-interpret the one-dimensional globalArray into
a multi-dimensional variable-length array so that compiler takes
care of the indexing math for me.*/
typedef double (*arr_t)[N][P];
const arr_t castArray = (arr_t)globalArray; /* Cast #1 */
double sum=0.0;
for (int i=0; i<M; i++)
for (int j=0; j<N; j++)
for (int k=0; k<P; k++)
sum += castArray[i][j][k];
return sum;
}
void initialize(int M, int N, int P, double threedimarray[M][N][P])
{
for (int i=0; i<M; i++)
for (int j=0; j<N; j++)
for (int k=0; k<P; k++)
threedimarray[i][j][k] = (double)(i*N*P + j*P + k);
}
int main(int argc, char **argv)
{
M = 10; N=1000; P=200;
globalArray
= malloc( M
*N
*P
* sizeof(double) );
typedef double (*arr_t)[N][P];
initialize(M, N, P, (arr_t)globalArray); /* Cast #2 */
double result = reduce();
printf("Reduced result: %f\n", result
); return 0;
}
CiNpbmNsdWRlIDxzdGRsaWIuaD4KI2luY2x1ZGUgPHN0ZGlvLmg+Cgpkb3VibGUgKiBnbG9iYWxBcnJheTsgLyogd29ya2luZyBmcm9tIGEgc2l0dWF0aW9uIHdoZXJlIHRoZSBhcnJheSBpcyBnbG9iYWwsIGRlY2xhcmVkIGVsc2V3aGVyZSAqLwppbnQgTSwgTiwgUDsgLyphcnJheSBkaW1lbnNpb25zIG5vdCBrbm93biB1bnRpbCBydW50aW1lICovCgpkb3VibGUgcmVkdWNlKCk7CmRvdWJsZSByZWR1Y2UoKQp7CgkvKiBIZXJlIEkgd2FudCB0byByZS1pbnRlcnByZXQgdGhlIG9uZS1kaW1lbnNpb25hbCBnbG9iYWxBcnJheSBpbnRvCgkgICBhIG11bHRpLWRpbWVuc2lvbmFsIHZhcmlhYmxlLWxlbmd0aCBhcnJheSBzbyB0aGF0IGNvbXBpbGVyIHRha2VzCgkgICBjYXJlIG9mIHRoZSBpbmRleGluZyBtYXRoIGZv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