Question

I have a problem assigning a pointer to a structure, to a pointer to a structure. I use gfortran 4.6.3, and the name of the file is test_pointer_struct.f08 so I am using the Fortran 2008 standard (as supported by gfortran 4.6.3).

Hera comes the code:

PROGRAM test_pointer_struct

type tSmall
  integer          :: a
  double precision :: b
end type tSmall

type tBig
  integer                   :: h
  type(tSmall), pointer     :: member_small
end type tBig

type(tBig)                  :: var_big
type(tSmall), pointer       :: var_small(:)

! We get an array of pointers to the small structure
allocate(var_small(3))
! Also allocate the member_small strucutre (not an array)
allocate(var_big%member_small)

var_big%member_small%a = 1
var_big%member_small%b = 2.0

! Now we want an element of the var_samall array of pointers, to point to the member_small in member_big
var_small(1) => var_big%member_small    ! <- I get a compilation error here

! And dissasociate the member_small (we still maintain access to memory space through var_small(1)
var_big%member_small => NULL()

END PROGRAM test_pointer_struct

When I complie this, I get the following error: Error: Se esperaba una especificación de límites para 'var_small' en (1) Which could be translated as Error: Limit specification expected for 'var_small' at (1)

What does this error mean?. What am I doing wrong?

Thank you very much in advance.

Was it helpful?

Solution

Fortran doesn't really do arrays of pointers. Your declaration

type(tSmall), pointer       :: var_small(:)

doesn't define var_small to be an array of pointers to things of type tsmall; rather it defines it to be a pointer to an array of things of type tsmall.

When I compile your code Intel Fortran gives the rather more helpful error message

The syntax of this data pointer assignment is incorrect: either 'bound spec' or 'bound remapping' is expected in this context.

which takes us to R735 in the Fortran 2003 standard. The compiler tries to parse var_small(1) not, as you wish, as a reference to the first element in an array of pointers but to either a bounds-spec-list or a bounds-remapping-list. The expression does not have the right syntax for either and the parse fails.

So that deals with the question of what the error means. What do you do about it ? That depends on your intentions. The usual suggestion is to define a derived type, along these lines

type myptr
    type(tsmall), pointer :: psmall
end type myptr

and then use an array of those

type(myptr), dimension(:), allocatable :: ptrarray

Personally I've never liked that approach and have never needed to use it (I write very simple programs). I expect that with Fortran 2003 there are better approaches too but without knowing your intentions I hesitate to offer advice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top