gpt4 book ai didi

pointers - 派生类型中的关联指针? gFortran 与英特尔

转载 作者:行者123 更新时间:2023-12-02 18:23:04 27 4
gpt4 key购买 nike

我想检查派生类型中的指针是否已定义。我编写了以下简单的代码来向您展示我的问题:

program test
implicit none

type y
real(8), pointer :: x(:)
end type y
type(y), pointer :: w(:)

allocate(w(2))
allocate(w(1)%x(2))

write(*,*) associated(w(1)%x), associated(w(2)%x)

end program test

使用 gFortran 4.4.1 编译此代码并在 Ubuntu 上运行它会得到结果:

T F

而使用 Intel Fortran 编译器 11.0 在 Windows Vista 上编译的相同代码提供:

T T

第一个结果(gFortran)是我真正期望的。但事实上,英特尔编译器提供了不同的结果,这让我担心我的代码可能不正确。我在这个例子中的指针做错了什么吗?有什么想法或解释吗?

非常感谢您的帮助!

最佳答案

您正在测试指针是否已关联,而无需在指针上显式使用 nullifycommon Fortran mistakes 上的一个很棒的页面备注(已删除代码示例):

Many people think that the status of a pointer which has never been associated is .not. associated. This is false. (...) When a pointer is declared its status is undefined, and cannot be safely queried with the associated intrinsic.

看起来 gfortran 编译器可能被设置为在声明时显式地使指针无效 - 您可能应该将其视为编译器自动将声明的变量设置为零,而不是指望这种行为。如果你想确定的话,你就自己将其作废。

编辑:

我正在阅读英特尔编译器指南,它指定了如何确保指针正确无效 - 您可以将派生类型设置为

type y
real(8), pointer :: x(:) => null()
end type y

但请注意,如链接文章中所述,这似乎仅限于 Fortran 95。

关于pointers - 派生类型中的关联指针? gFortran 与英特尔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1909406/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com