Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have a pointer to an item in an allocatable array component?

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

and

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?

like image 465
Phil H Avatar asked Oct 16 '10 08:10

Phil H


1 Answers

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.

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.

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
like image 169
Deditos Avatar answered Sep 30 '22 04:09

Deditos