【发布时间】:2015-02-27 05:21:03
【问题描述】:
我想写一个在fortran中返回一个可分配数组的函数
program test
implicit none
real a(3)
real, allocatable :: F18(:)
a = (/1,2,3/)
print *, F18(a)
end program test
function F18(A)
implicit none
real A(:) ! An assumed shape array
real F18(size(A,1)) ! The function result itself is
! the second dimension of A.
F18 =A !
end function F18
预计会在屏幕上打印“1 2 3”,但出现错误:
forrtl: 严重 (157): 程序异常 - 访问冲突
有什么问题?
另外,我试过这样的代码:
program test
implicit none
real a(3)
real, allocatable :: F18(:)
a = (/1,2,3/)
print *, F18(a,3)
end program test
function F18(A,n)
implicit none
integer n
real A(:) ! An assumed shape array
real F18(size(A,1)) ! The function result itself is
! the second dimension of A.
F18 =A !
end function F18
在编译过程中我得到:
Intel(R) Visual Fortran Intel(R) 64 Compiler XE for applications running on Intel(R) 64, Version 14.0.4.237 Build 20140805
Copyright (C) 1985-2014 Intel Corporation. All rights reserved.
D:\Fortran\Elephant.f90(6): error #6351: The number of subscripts is incorrect. [F18]
print *, F18(a,3)
-------------^
compilation aborted for D:\Fortran\Elephant.f90 (code 1)
我真的对fortran的功能感到困惑。
在fortran中调用数组值函数的正确方法是什么?
@Fortranner
【问题讨论】:
-
对于 1 级数组,Fortran 2003 引入了使用方括号
[]来分隔数组构造函数。所以,a = (/1,2,3/)可以写成a = [1, 2, 3]。它更易于阅读。