fortran指针数组与c语言数组,Fortran可分配数组和指针之间的等价性

是的,由于c_f_pointer的限制,这是一个问题.正如您所发现的那样,内部c_f_pointer仅支持从索引1开始的边界.人们经常声明Fortran是一种单索引语言,但事实并非如此.一个索引只是默认值,Fortran长期支持声明程序员想要的任何起始绑定.因此,c_f_pointer强制您使用一个索引是向后退一步.但是使用Fortran 2003有一个修复:指针边界重新映射:

arr (0:n-1) => arr

而不是1:n,或任何你想要的.

然后将数组传递给子例程,它将接收预期的边界.

编辑:改进演示程序,显示allocatables和指针之间的区别.指针传递数组的边界.一个常规数组传递形状…如果你愿意,可以在子程序中声明第一个维度,然后让形状控制第二个维度.

module mysubs

implicit none

contains

subroutine testsub ( ptr, alloc, start, array )

real, pointer, dimension (:) :: ptr

real, dimension (:), intent (in) :: alloc

integer, intent (in) :: start

real, dimension (start:), intent (in) :: array

write (*, *) "pointer in sub:", lbound (ptr, 1), ubound (ptr, 1)

write (*, *) ptr

write (*, *) "1st array in sub:", lbound (alloc, 1), ubound (alloc, 1)

write (*, *) alloc

write (*, *) "2nd array in sub:", lbound (array, 1), ubound (array, 1)

write (*, *) array

return

end subroutine testsub

end module mysubs

program test_ptr_assignment

use mysubs

implicit none

real, pointer, dimension(:) :: test

real, allocatable, dimension(:) :: alloc1, alloc2

real, allocatable, dimension(:) :: alloc1B, alloc2B

allocate ( test (1:5), alloc1 (1:5), alloc1B (1:5) )

test = [ 1.0, 2.0, 3.0, 4.0, 5.0 ]

alloc1 = test

alloc1B = test

write (*, *) "A:", lbound (test, 1), ubound (test, 1)

write (*, *) test

call testsub (test, alloc1, 1, alloc1B )

test (0:4) => test

allocate ( alloc2 (0:4), alloc2B (0:4) )

alloc2 = test

alloc2B = test

write (*, *)

write (*, *) "B:", lbound (test, 1), ubound (test, 1)

write (*, *) test

call testsub (test, alloc2, 0, alloc2B)

stop

end program test_ptr_assignment

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值