本文介绍了POINTER和ALLOCATABLE之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

这两个代码有什么区别

  type Foo 
real,allocatable :: bar(:)
结束类型

  type Foo 
real,pointer :: bar(:)
end type

特别是当涉及到以下代码时:

  type(Foo):: myfoo 
allocate(myfoo%bar(10))


解决方案

在这种情况下,我看不出任何主要差异。

一般来说,。但在Fortran 90/95 POINTER阵列中更加灵活。例如,不可能将ALLOCATABLE数组用作派生类型的组件。 Fortran 2003修复了这个问题。因此,尽可能使用ALLOCATABLE数组。



编辑

程序在尝试分配已分配的实体方面的行为显着不同。如果实体是ALLOCATABLE,你会得到运行时错误。该程序

 程序main 

隐式无

TYPE :: foo
REAL,DIMENSION(:),ALLOCATABLE :: bar
END TYPE foo

TYPE(foo):: my_foo

ALLOCATE(my_foo%bar (10))
ALLOCATE(my_foo%bar(10))

END PROGRAM main


使用gfortran编译的

会导致这样的错误信息:

$ p $ Fortran运行时错误:试图分配已经分配的变量'my_foo'

相比之下,您可以使用POINTER来做这些事情。


what is the difference between these two codes

type Foo
   real, allocatable :: bar(:)
end type

and

type Foo
   real, pointer :: bar(:)
end type

in particular when it comes to the following code:

type(Foo) :: myfoo
allocate(myfoo%bar(10))
解决方案

I do not see any principal difference in that scenario.

In general, ALLOCATABLE arrays are more efficient. But in Fortran 90/95 POINTER arrays were more flexible. For example, it was not possible to use ALLOCATABLE arrays as components of derived types. Fortran 2003 fixed that issue. So use ALLOCATABLE arrays when you can.

EDIT

Just want to mention significant difference in behavior of the program on the attempt to allocate already allocated entity. If the entity is ALLOCATABLE you'll get run-time error. The program

PROGRAM main

  IMPLICIT NONE

  TYPE :: foo
    REAL, DIMENSION(:), ALLOCATABLE :: bar
  END TYPE foo

  TYPE(foo) :: my_foo

  ALLOCATE (my_foo%bar(10))
  ALLOCATE (my_foo%bar(10))

END PROGRAM main

compiled with gfortran results in such error message:

Fortran runtime error: Attempting to allocate already allocated variable 'my_foo'

In contrast you can do such things with POINTERs.

这篇关于POINTER和ALLOCATABLE之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-08 14:10