我正在尝试将在C中初始化的4D数组传递给FORTRAN函数。根据前一个question的建议,我首先使用单个malloc将数据数组分配为连续数据,然后分配指针指针,使它们最终指向数据数组。此方法适用于3D阵列。但是,当我转到4D阵列时,我没有得到FORTRAN中预期的值。当我为C数组malloc内存时,是否需要改变某些事情> 3个维度或者alloc_4D_double函数中是否有错误?
代码摘录:
#include <stdio.h>
#include <stdlib.h>
double f_function(double ****);
double ****alloc_4D_double(int wlen, int xlen, int ylen, int zlen, double *ary)
{
int i,j,k;
double ****multiDary = (double****)malloc(wlen*sizeof(double***));
for (i = 0; i < wlen; i++)
{
multiDary[i] = (double***)malloc(xlen*sizeof(double**));
for (j = 0; j < xlen; j++)
{
multiDary[i][j] = (double**)malloc(ylen*sizeof(double*));
for (k = 0; k < ylen; k++)
{
multiDary[i][j][k] = (double*)malloc(zlen*sizeof(double));
}
}
}
for (i = 0; i < wlen; i++)
{
for (j = 0; j < xlen; j++)
{
for (k = 0; k < ylen; k++)
{
multiDary[i][j][k] = &ary[zlen*(k + ylen*(j + xlen*i))];
}
}
}
return multiDary;
}
int main ( void ) {
// create contiguous memory
double *data1D = (double*)malloc(2 * 4 * 10 * 10 * sizeof(double));
// map memory locations to allow use of array syntax
double ****exposure4D = alloc_4D_double(2, 4, 10, 10, exposure1D);
// assign a value
data[0][1][4][4] = 0.777;
// pass the pointer to FORTRAN
f_funtion(data1D)
return 0;
}
和
integer(4) function f_function(data) BIND(C)
use, intrinsic :: iso_c_binding
implicit none
!
real(C_DOUBLE) , intent(in), dimension(2,4,10,10) :: data
// this value does not evaluate to 0.7777
write(*,*), data(1,2,5,5)
// this value does evaluate to 0.7777
write(*,*), data(1,1,9,2)
end function f_function