fork download
  1.  
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4.  
  5. double * globalArray; /* working from a situation where the array is global, declared elsewhere */
  6. int M, N, P; /*array dimensions not known until runtime */
  7.  
  8. double reduce();
  9. double reduce()
  10. {
  11. /* Here I want to re-interpret the one-dimensional globalArray into
  12. a multi-dimensional variable-length array so that compiler takes
  13. care of the indexing math for me.*/
  14. typedef double (*arr_t)[N][P];
  15.  
  16. const arr_t castArray = (arr_t)globalArray; /* Cast #1 */
  17.  
  18. double sum=0.0;
  19. for (int i=0; i<M; i++)
  20. for (int j=0; j<N; j++)
  21. for (int k=0; k<P; k++)
  22. sum += castArray[i][j][k];
  23. return sum;
  24. }
  25.  
  26. void initialize(int M, int N, int P, double threedimarray[M][N][P])
  27. {
  28. for (int i=0; i<M; i++)
  29. for (int j=0; j<N; j++)
  30. for (int k=0; k<P; k++)
  31. threedimarray[i][j][k] = (double)(i*N*P + j*P + k);
  32. }
  33.  
  34. int main(int argc, char **argv)
  35. {
  36. M = 10; N=1000; P=200;
  37. globalArray = malloc( M*N*P* sizeof(double) );
  38.  
  39. typedef double (*arr_t)[N][P];
  40. initialize(M, N, P, (arr_t)globalArray); /* Cast #2 */
  41.  
  42. double result = reduce();
  43. printf("Reduced result: %f\n", result );
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0.02s 25056KB
stdin
Standard input is empty
stdout
Reduced result: 1999999000000.000000