我可以有一个指向可分配数组组件中的项的指针吗? [英] Can I have a pointer to an item in an allocatable array component?

查看:114
本文介绍了我可以有一个指向可分配数组组件中的项的指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用户定义的类型 vector 。在另一种类型中,我有一个可分配的向量数组。我想要一个指向这个可分配数组的单个向量的指针。所以我想我会这样做:

I have a user-defined type vector. In another type, I have an allocatable array of vectors. I want to have a pointer to a single vector from this allocatable array. So I thought I would do this:

type another_type
  type(vector),allocatable,target::my_vectors(:)
end type

type(vector),pointer::pointed_vec

但编译时,编译器会抱怨:

But when I compile, the compiler complains that:

This attribute specification is not valid for a component definition statement.

我可以有指向可分配数组中单个项的指针吗?是否有可能?

Can I have a pointer to a single item from an allocatable array? Is it possible?

推荐答案

只有变量或派生类型的实际实例可能具有 TARGET 属性。所以,第二个类型定义中的allocatable不能作为目标,因为这只是对类型应该是什么样子的描述,如果你愿意,可以使用模板。

Only actual instances of variables or derived types may have the TARGET attribute. So, the allocatable in the second type definition cannot be a target as this is just a description of what the type should look like, a template if you like.

然而,您可以给出一个类型为 TARGET 属性的实例,然后使用适当声明的Fortran指针指向它的任何组件部分。

However, you can give a real instance of the type the TARGET attribute and then point to any of it's component parts with appropriately declared Fortran pointers.

编辑:另一种方法是,也许更多的是为了赋予 POINTER 类型的向量数组,属性,这隐含地使它既是合法的指针,也可以用来分配内存。在你用它分配内存之后,你必须确保你不会重新指定指针(在下面的例子中为 v ),因为那样你就会有一个泄漏。

Editted: An alternative, and probably more what you're after, is to give the vector array in the type the POINTER attribute only, which implicitly makes it both legitimate pointee and may be used to allocate memory. You just have to make sure that you don't reassign the pointer (v in example below) after you've used it to allocate the memory, because then you'll have a leak.

PROGRAM so_pointtype

  IMPLICIT NONE

  TYPE vec
    INTEGER :: x = 2, y = 3
  END TYPE vec

  TYPE foo
    TYPE(vec),POINTER :: v(:)
  END TYPE foo

  TYPE(foo) :: z
  TYPE(vec),DIMENSION(:),POINTER :: p2 => NULL()

  ALLOCATE(z%v(3))

  PRINT*,z%v(:)

  p2 => z%v(:)

  PRINT*,p2

END PROGRAM so_pointtype

这篇关于我可以有一个指向可分配数组组件中的项的指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆