首页 > 解决方案 > 指向派生类型的指针的声明可以是未定义的吗?

问题描述

我有一个小代码声明一个指向派生类型数组的指针,该数组具有一个字段,该字段是另一个派生类型的可分配数组,具有一个实变量作为字段。使用 gnu fortran (8.2) 我为数组中的每个位置或作为向量获得不同的结果。

使用 intel fortran (2019.4) 编译成功。

program test
implicit none
integer, parameter :: length = 2
real(8), dimension(length) :: a, b
integer :: i

type point
   real(8) :: x
end type point

type stored
   type(point), dimension(:), allocatable :: np
end type stored

type(stored), dimension(:), pointer :: std=>null()


allocate(std(1))
allocate(std(1)%np(length))
std(1)%np(1)%x = 0.3d0
std(1)%np(2)%x = 0.3555d0

do i = 1, length
   write(*, "('std(1)%np(',i1,')%x = ',1e22.14)") i, std(1)%np(i)%x
end do
do i = 1, length
   write(*, "('std(1)%np(1:',i1,') = ',2e22.14)") i, std(1)%np(1:i)%x
end do
a = std(1)%np(1:2)%x
b = [std(1)%np(1)%x, std(1)%np(2)%x]
if (norm2(a - b) .gt. 1d-3) then
   write(*,*) 'failure'
else
   write(*, *) 'success'
end if
end program test

代码成功终止,但使用 gfortran 在屏幕上获得“失败”并且上面的打印不一致,使用英特尔编译器在屏幕上获得“成功”并且上面的打印一致。

标签: fortrangfortran

解决方案


It's not clear to me what your question is, unless it's the title. If so, no, pointers to derived types are fine. Your program correctly allocates std as an extent-1 array and then allocates std(1)%np(2). It then assigns to the x subcomponents of both np elements. Looks fine to me.

There are several things that could potentially cause "failure" - you should run the gfortran code in the debugger to see what is going wrong.


推荐阅读