1

I've written a small test case program in FORTRAN 90 which initializes a 3d array in slices. Can this same behavior be easily replicated in C?

  program fortranEngine

  real(4) , dimension(10,10) :: tmp
  real(4) , dimension(10,10,3) :: p    

  tmp = RESHAPE( [  0.973, 1.053, 0,     0,     0,     0,     0,     0,     0,     0, &
                    1.053, 1.080, 0,     0,     0,     0,     0,     0,     0,     0, &
                    1.010, 0.408, 0.442, 0,     0,     0,     0,     0,     0,     0, &
                    1.119, 0.900, 0.399, 0.762, 0,     0,     0,     0,     0,     0, &
                    1.211, 0.975, 0.845, 0.952, 1.105, 0,     0,     0,     0,     0, &
                    1.248, 1.016, 0.485, 0.000, 0.000, 1.110, 0,     0,     0,     0, &
                    1.225, 1.123, 1.056, 0.000, 0.000, 0.949, 0.832, 0,     0,     0, &
                    1.138, 1.232, 1.089, 1.050, 0.930, 0.402, 0.789, 0.774, 0,     0, &
                    1.149, 1.406, 1.201, 1.052, 0.416, 0.878, 0.896, 0.431, 1.144, 0, &
                    1.351, 1.255, 1.290, 1.358, 1.240, 1.228, 1.257, 1.140, 1.123, 1.228] &
                    , [10,10] )    

    p(:,:,1) = tmp    

    ...

    end program fortranEngine
javacavaj
  • 2,901
  • 5
  • 39
  • 66

2 Answers2

2

You can more or less do it in C99 or C2011, but it isn't as convenient as in Fortran. Beware initialization order; Fortran does it in one order (column-major) and C does it in the other (row-major). Ignoring that, you can do:

float tmp[10][10] =
{
    { 0.973, 1.053, 0,     0,     0,     0,     0,     0,     0,     0,    },
    { 1.053, 1.080, 0,     0,     0,     0,     0,     0,     0,     0,    },
    { 1.010, 0.408, 0.442, 0,     0,     0,     0,     0,     0,     0,    },
    { 1.119, 0.900, 0.399, 0.762, 0,     0,     0,     0,     0,     0,    },
    { 1.211, 0.975, 0.845, 0.952, 1.105, 0,     0,     0,     0,     0,    },
    { 1.248, 1.016, 0.485, 0.000, 0.000, 1.110, 0,     0,     0,     0,    },
    { 1.225, 1.123, 1.056, 0.000, 0.000, 0.949, 0.832, 0,     0,     0,    },
    { 1.138, 1.232, 1.089, 1.050, 0.930, 0.402, 0.789, 0.774, 0,     0,    },
    { 1.149, 1.406, 1.201, 1.052, 0.416, 0.878, 0.896, 0.431, 1.144, 0,    },
    { 1.351, 1.255, 1.290, 1.358, 1.240, 1.228, 1.257, 1.140, 1.123, 1.228 },
};
float p[3][10][10];    

for (int i = 0; i < 3; i++)
    memmove(p[i], tmp, sizeof(tmp));

Note that I moved the dimension [3] from the end of the declaration to the start of the declaration, though. The other way around would not make much sense in C. So, the notation is more or less available, but details of storage management make it less than obvious how to achieve exactly what you want.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
1

Is this easy enough?

for(int i = 0 ; i < 10 ; ++i) 
    for(int j = 0 ; j < 10 ; ++j )
        p[0][i][j] = tmp[i][j] ;
Theodore Norvell
  • 15,366
  • 6
  • 31
  • 45