【问题标题】:Unexpected data declaration error in Fortran when creating array创建数组时在 Fortran 中出现意外的数据声明错误
【发布时间】:2012-11-17 18:58:23
【问题描述】:

我编写了一个简单的测试程序来演示我在编译某些 Fortran 代码时收到的数据声明错误。编译错误发生在我试图创建任意大小的数组的行上。在 C 代码中,我相信这可以通过简单的malloc 来完成,但这种方法在 Fortran 中可能没有用。

这里出了什么问题,我该如何解决?我在GNU/Linux 上使用gfortran 编译器,所以我认为可以使用所有受支持的语言功能。

这是我的测试程序:

program test
implicit none
    integer num1, num2

    print *, 'Starting...'
    num1 = 10
    num2 = 11
    call sub(num1, num2)
    print *, 'Done.'

end program



subroutine sub(num1, num2)
    integer num1, num2
    integer num3

    num3 = num1 + num2 - 1
    integer A(num3)

    do i = 1,num3
        A(i) = i
    end do

    print *, 'Now printing out vector'

    do i = 1,num3
        print *, A(i)
    end do
end subroutine

这是用于编译我的简单测试程序的cmake 脚本:

cmake_minimum_required (VERSION 2.6)
project (test Fortran)

add_executable( test
test.f90
) # end

编译此程序时,我收到以下错误:

/media/RESEARCH/SAS2-version2/test-Q-filter/test-Fcreation/test.f90:20.16:

 integer A(num3)
                1
Error: Unexpected data declaration statement at (1)
/media/RESEARCH/SAS2-version2/test-Q-filter/test-Fcreation/test.f90:23.10:

  A(i) = i
          1
Error: Unexpected STATEMENT FUNCTION statement at (1)
make[2]: *** [CMakeFiles/test.dir/test.f90.o] Error 1
make[1]: *** [CMakeFiles/test.dir/all] Error 2
make: *** [all] Error 2

【问题讨论】:

    标签: fortran


    【解决方案1】:

    问题是,因为你在普通语句之后放置了数据声明语句。

    你不必使用用户定义的动态分配,所谓的自动分配就足够了。 (它也适用于 C99 AFAIK,但仅适用于堆栈分配)。 直接替换

    num3 = num1 + num2 - 1
    integer A(num3)
    

    integer A(num1 + num2 - 1)
    integer num3
    
    num3 = num1 + num2 - 1
    

    .

    不幸的是,你不能只写

    integer :: num3 = num1 + num2 - 1
    

    因为变量将隐式为SAVE,并且必须在编译时知道 num1 和 num2。

    注意我没有检查其他错误。

    作为一个完全不同的问题,我建议您对所有子程序使用 mudules。在这种简单的情况下,也可以使用内部子程序。这样您就有了一个明确的界面,您可以检查调用的一致性并使用更高级的功能。

    【讨论】:

    • 谢谢弗拉基米尔;这很好用,而且实现起来很简单。内部子程序会很有用。
    • 另请注意,显式数组分配是由 allocate 语句完成的,但数组必须是可分配的(首选)或指针。
    • allocate() 是我比较熟悉的 C 语言函数 malloc()。感谢弗拉基米尔的启发性评论。
    猜你喜欢
    • 2016-08-28
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 2021-11-24
    • 2021-08-12
    相关资源
    最近更新 更多