views:

160

answers:

1

Hello,

I would like to check if a pointer inside a derived type has already been defined or not. I wrote the following simple code to show you my problem:

program test
implicit none

type y
    real(8), pointer :: x(:)
end type y
type(y), pointer :: w(:)

allocate(w(2))
allocate(w(1)%x(2))

write(*,*) associated(w(1)%x), associated(w(2)%x)

end program test

Compiling this code with gFortran 4.4.1 and running it on Ubuntu gives the result:

T F

whereas the same code compiled on Windows Vista with the Intel Fortran compiler 11.0 provides:

T T

The first result (gFortran) is what I am actually expecting. But the fact that the Intel compiler provides a different result makes me fear my code might not be correct. Am I doing something terribly wrong with the pointers in this example? Any idea or explanation?

Many thanks in advance for your help!

+5  A: 

You are testing to see if a pointer is associated without explicitly using nullify on the pointers. A great page on common Fortran mistakes remarks (with the code sample removed):

Many people think that the status of a pointer which has never been associated is .not. associated. This is false. (...) When a pointer is declared its status is undefined, and cannot be safely queried with the associated intrinsic.

It looks like the gfortran compiler may be set up to explicitly nullify pointers on declaration - you should probably think of this like the compiler automatically setting declared variables to zero, and not count on that behavior. If you want to be sure, you will nullify it yourself.

Edit:

I'm reading through the Intel compiler guide, and it specifies how to make sure that the pointer are nullified correctly - you can set up your derived type as

type y
    real(8), pointer :: x(:) => null()
end type y

Note, however, that it seems like this is limited to Fortran 95, as mentioned in the linked article.

Tim Whitcomb
Thank you very much!! This was indeed the problem. The solution you suggest works very well, with both the Intel compiler and gFortran.
remek