检查数组是否可以在fortran中分配

时间:2017-08-27 15:27:01

标签: arrays fortran intel-fortran allocatable-array

在fortran中,可以使用allocated语句检查是否分配了可分配数组:

program test_allocated
  integer :: i = 4
  real(4), allocatable :: x(:)

  print *, 'before allocation of x'
  print *, 'allocated(x)'
  print *, allocated(x)

  allocate(x(i))
  print *, 'after allocation of x'
  print *, 'allocated(x)'
  print *, allocated(x)

end program test_allocated

但是,是否有可能以某种方式检查常规数组是否被声明为可分配?以下代码

program test_allocated
  integer :: i = 4
  real(4), allocatable :: x(:)
  real(4)::y
  print *, 'before allocation of x'
  print *, 'allocated(x)'
  print *, allocated(x)
  print *, 'allocated(y)'
  print *, allocated(y)
  allocate(x(i))
  print *, 'after allocation of x'
  print *, 'allocated(x)'
  print *, allocated(x)
  print *, 'allocated(y)'
  print *, allocated(y)
end program test_allocated

抛出错误

D:\TEMP\FortranTest\ifort>ifort test.f90
Intel(R) Visual Fortran Intel(R) 64 Compiler XE for applications running on Inte
l(R) 64, Version 13.0.1.119 Build 20121008
Copyright (C) 1985-2012 Intel Corporation.  All rights reserved.

test.f90(9): error #6547: The ARRAY argument of the ALLOCATED inquiry intrinsic
function shall be an allocatable array.   [Y]
  print *, allocated(y)
---------------------^
test.f90(15): error #6547: The ARRAY argument of the ALLOCATED inquiry intrinsic
 function shall be an allocatable array.   [Y]
  print *, allocated(y)
---------------------^
compilation aborted for test.f90 (code 1)

也许存在另一种询问数组性质的陈述或方法?

1 个答案:

答案 0 :(得分:1)

某些编译器将数组的元数据存储在涂料数组描述符中,包括可分配性,连续性,元素存储大小,定义状态(如果是指针)之类的属性……语言内部需要它们来检查特定接口的匹配过程调用。

因此,在技术上可能检查这种元信息,但几乎没有用。同样,Fortran是静态类型的,编译器能够在编译时进行所有这些检查。

此外,该语言的设计方式是,只有在您明确声明它是可分配的(或指针)时,才可以处理对变量(或虚拟参数)的分配。在所有其他情况下,您都可以使用数组而无需理会它的分配方式。

请参见this forum thread

  

一旦分配了可分配的数组,它现在就是一个与其他数组一样“好”的数组,可以将其作为实际参数传递给过程(或C)   函数),甚至不需要知道它是可分配的。我可能会补充说,这同样适用于指针数组,尽管对此情况有一点警告(涉及指针数组的可能性)。   可能指向不连续的切片。

对于您的特定情况,您尝试将内部函数allocated与不可分配的数组y一起使用,从而产生错误。您无需在使用此函数之前检查数组是否可分配,您只需要知道一下,如果您未明确将其声明为allocatable(就像对x所做的那样) ),不是

以同样的方式,如果要在函数或子例程中管理变量的分配,则只需将哑参数声明为可分配变量,即可确保过程仅接受可分配变量(与指针相同) )。


如果您有足够的理由戳探变量的内部表示并且知道自己在做什么,则可以在其他问题上参考@VladmirF的this answer或深入参考手册。您的特定编译器。此外,该标准的最新版本还指定了标准化的数组描述符,旨在与c代码实现互操作性。


最后,当您在此问题中标记英特尔时,我将带您到Intel compiler reference on the matter,在这里您可以看到:

  

使用数组描述符的不利之处在于它会增加出错的机会。此外,相应的代码不可移植。具体来说:

     

如果描述符定义不正确,程序可能会访问错误的内存地址,可能会导致常规保护错误。

     

数组描述符格式特定于每个Fortran编译器。使用数组描述符的代码不能移植到其他编译器或平台。

     

数组描述符格式将来可能会更改。

     

如果描述符是由编译器生成的,则用户无法对其进行修改。更改现有描述符的字段是非法的。

     

使用IA-32架构的系统上当前Intel®Fortran数组描述符的组件如下:

     

字节0到3包含基地址。

     

(...)

     

字节12到15包含一组用于存储有关阵列信息的标志。这包括:

     

位1(0x01):数组已定义-如果已定义数组(已分配存储),则设置此字段。

     

(...)

     

位8(0x80):如果指向的数组是ALLOCATABLE,则设置该值。

     

其他位保留。