How to pass single dimension array from fortran to

2019-05-28 08:12发布

This question already has an answer here:

I am passing a single dimension array to function from Fortran program to a C. The function get called but the values it gets are garbage. Here is my code

File: abc.f

program test
    real*4 :: a(4)
    data a / 1,2,3,4 /
    call test_func(a)
end program testFile: 

File: abc.c

int test_func(double a[]) {
    int i;

    for(i=0;i<4;i++) {
        printf("%f\n",a[i]);
    }

    return 0;
}

But if i pass integer instead of array then it is successfully passed.

1条回答
Root(大扎)
2楼-- · 2019-05-28 08:46

You should change your signature to

 void test_func(float a[], int arraylength);

Not only are you passing the wrong datatype, you are also reading more memory, then you passed in, which accounts for the garbage.

real is 4 bytes and double is 8 bytes, so you are reading twice as much memory beyond your array limit as you passed in which will cause undefined behaviour.

Another good idea would be to pass the length of the array as well. I don't know how this is in Fortran, but in C you are just reading a pointer, without any information how long that array is.

查看更多
登录 后发表回答