Pointers 如何在Fortran中获取数组指针的地址?
我想获取数组指针的地址。原型代码如下所示:Pointers 如何在Fortran中获取数组指针的地址?,pointers,fortran,Pointers,Fortran,我想获取数组指针的地址。原型代码如下所示: program main implicit none type foo integer, allocatable :: i(:) integer j end type type(foo) a integer, pointer :: ai(:) ai => a%i print *, "The address of a is ", loc(a)
program main
implicit none
type foo
integer, allocatable :: i(:)
integer j
end type
type(foo) a
integer, pointer :: ai(:)
ai => a%i
print *, "The address of a is ", loc(a)
print *, "The address of a%i is", loc(ai) ! <--- I expect the same address as a.
end program main
主程序
隐式无
foo型
整数,可分配::i(:)
整数j
端型
类型(foo)a
整数,指针::ai(:)
ai=>a%i
打印*,“a的地址”,loc(a)
打印*,“a%i的地址为”,loc(ai) Fortran不保证用户定义类型的第一项与该用户定义类型的地址相同。可能在项目之前有一个标题。也许有一些填充物。也许编译器以不同的顺序存储这些项。也许不同的编译器做的不同。这些都没有指定。所以你的期望可能不会实现。在Fortran中几乎不需要地址。你想干什么?如果您正在连接到C,ISO_C_绑定将提供C_LOC
编辑以响应注释。如果您的目标是通过省略前导的“a%”来简化变量名,那么可以使用指针创建访问相同存储的替代变量。你不必试图用指针超越语言。例如:
program main
implicit none
type foo
integer, pointer :: i(:)
integer j
end type
type(foo) a
integer, pointer :: ai(:)
allocate ( a%i (5) )
a%i = [ 2, 5, 1, 3, 9 ]
ai => a%i
write (*, '( "a%i=", 5(2X,I2) )' ) a%i
write (*, '( "ai=", 5(2X,I2) )' ) ai
end program main
输出为:
a%i= 2 5 1 3 9
ai= 2 5 1 3 9
你不能,反正不用标准Fortran
请注意,您的期望是错误的
loc
是一个扩展。它所做的是特定于处理器的,但通常会为您提供参数所表示的数据对象的地址的整数表示。(F2003标准的C_LOC大致相当。)。在这种情况下,数据对象是一个可分配的数组。在我所知道的所有处理器中,该阵列的存储不在承载可分配组件的派生类型对象的存储中。派生类型对象只包含一个描述数组存储位置(以及它的大小等)的描述符,而不是数组本身的存储。我正在设计一个包含数据数组的数据类型。用户希望在不键入“%”的情况下显式使用数据数组以简化代码,并且Fortran没有索引运算符。在某个阶段,需要数据类型中的其他信息,因此我必须从数据数组的地址获取数据类型。如果OP在代码中使用taht,我更愿意使用可分配组件并添加目标属性。它可以防止内存泄漏。@VladimirF,这也是我的第一个方法,因为你说的原因。编译器告诉我,用户定义类型的组件不允许使用“可分配,目标”组合。