I understand that extra care needs to be taken when allocating memory in C to ensure a 2d array is contiguous, but I still don't get expected outcomes when I pass it to Fortran. Below is a toy version of my attempt: A main.c file which allocates memory for a 2d array and assigns a value to each element, and a foo.f90 file that prints out elements of the 2d array.
#include <stdio.h>
#include <stdlib.h>
void foo_(double **,int *,int *);
int main() {
int i, j, cols, rows;
double *_x, **x;
cols = 3;
rows = 2;
// Allocate memory
_x = malloc(rows*cols*sizeof(double));
x = malloc(cols*sizeof(double *));
for(i=0;i<cols;i++)
x[i] = &(_x[rows*i]);
// Generate elements for the 2d array
for(i=0;i<cols;i++)
for(j=0;j<rows;j++)
x[i][j] = i*j;
// Call Fortran subroutine foo
foo_(x,&rows,&cols);
return EXIT_SUCCESS;
}
foo.h
subroutine foo(x,rows,cols)
use iso_c_binding
implicit none
integer(c_long), intent(in) :: rows,cols
real(c_double), intent(in), dimension(rows,cols) :: x
integer :: i,j
do i = 1,cols
do j = 1,rows
print *, j,i,x(j,i)
end do
end do
end subroutine
As output, I expect a list of array elements. Instead, I get the following output
1 1 1.1654415706619996E-316
2 1 1.1654423611670330E-316
Segmentation fault (core dumped)