如何从FORTRAN传递一维数组到c [英] How to pass single dimension array from fortran to c

查看:405
本文介绍了如何从FORTRAN传递一维数组到c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我传递一个一维数组从Fortran程序的功能为C.
该函数被调用,但它得到的值是垃圾。
这里是我的code

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

文件:abc.f

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

文件:abc.c

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.

推荐答案

您应该签名改为

 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.

真正 4字节和双击是8个字节,所以你正在阅读的两倍多的内存超出你的阵列限制你通过了,这将导致不确定的行为。

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.

另一个好主意将是传递数组的长度为好。我不知道这是怎么在 Fortran语言,而在 C 你只是读一个指针,没有任何信息该数组有多长。

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.

这篇关于如何从FORTRAN传递一维数组到c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆