I have a fortran subroutine like this which expects a 3d array and prints the size along each dimension:
subroutine printarray(arr)
real*8 :: arr(:,:,:)
print*, "Dimensions of arr -> ", size(arr(:,1,1)), size(arr(1,:,1)), size(arr(1,1,:))
end subroutine printarray
Now I want to pass a 3d array from a C program to this subroutine.
I attempted it in many ways, none of them worked.
Attempt 1:
#include <stdio.h>
#include <stdlib.h>
void printarray_(double *);
int main(int argc, char *argv[])
{
double *ap;
ap = (double *) malloc(sizeof(double) * 10 * 10 * 2);
printarray_(ap);
if(ap != NULL)
free(ap);
return 0;
}
Output is : 1 1 1
One issue here is I haven't explicitly specified the size of each dimension in my C code itself, so I cannot expect Fortran to figure it out. So I tried it differently:
Attempt 2:
#include <stdio.h>
#include <stdlib.h>
void printarray_(double ***);
int main(int argc, char *argv[])
{
int i;
int j;
double ***a;
a = (double ***) malloc(sizeof(double **) * 200);
for(i = 0;i < 10;i++)
{
a[i] = (double **) malloc(sizeof(double *) * 10);
for(j = 0;j < 10;j++)
{
a[i][j] = (double *) malloc(sizeof(double) * 2);
}
}
printarray_(a);
for(i = 0; i < 10;i++)
{
for(j = 0;j < 10;j++)
{
if(a[i][j] != NULL)
free(a[i][j]);
}
if(a[i] != NULL)
free(a[i]);
}
if(a != NULL)
free(a);
return 0;
}
Here, the output is : 289 289 1
What is the correct way of passing multidimensional arrays to Fortran subroutines from C programs, such that the size function in fortran picks up correct size of each dimension?