Hi,
Actually this is a how to do type of question.
Suppose that I have a derived type with a large array component
type mytype
integer ,private, dimension (1000) :: data
.....
I want to declare a function which will return a pointer that points a certain part of this data.
size of the array should be dynamical.
Is there any way to do this?
I have tried pointer valued function defined as a bound procedure to mytype
....
contains
procedure access_data
end type
function access_data(this,i) result( part_data)
class(mytype), target :: this
integer :: i
integer , pointer , dimension(:) ::part_data
part_data=> this%data(1:10)
end function
to call this function
I declared an integer pointer array with
integer , dimension(:) , pointer :: get_data
get_data=this%data(1)
to test I put
print*, get_data(1)
and it gives me seg fault.
What am i doing wrong or is my way totally wrong?
Dundar.
链接已复制
3 回复数
You should use pointer assignment (i.e., "=>") to get a pointer to the function result, or regular assignment (i.e., "=") if you want to store the function result in an array. The following code should work:
[fortran]module mod1
implicit none
save
integer, private :: i
type mytype
integer, private :: data(1000) = [(i, i = 1, 1000)]
contains
procedure :: access_data
end type
contains
function access_data(this,N) result(part_data)
integer, pointer ::part_data(:)
class(mytype), target, intent(IN) :: this
integer, intent(IN) :: N
part_data=> this%data(1:N)
end function
end module
use mod1
implicit none
integer, parameter :: N = 10
type(mytype), target :: var
integer, pointer :: get_pointer(:)
integer :: get_values(N)
get_pointer => var%access_data(N)
print '("get_pointer:" / (5I5))', get_pointer
get_values = var%access_data(N)
print '("get_values:" / (5I5))', get_values
end[/fortran]
Thank you very much,
I have implemented this to my code and observed significant increase in performance.
During a do loop I have been accessing to some data component of a derived type and
using pointers to access this data improved the performance.
Thanks again.
Interesting. It should actually have the opposite effect ---that is, decrease in performance as a result of inhibited optimizations.
If you're using pointers only as alias for derived type components, the better option is the ASSOCIATE construct:
[fortran]implicit none
integer :: i
integer, parameter :: N = 100
type mytype
integer :: data(N) = [(i, i = 1, N)]
end type
type(mytype) :: var
associate (even => var%data(2::2), &
odd => var%data(::2))
print '("even entries:" / (10I5))', even
print '("odd entries:" / (10I5))', odd
end associate
end[/fortran] Besides matching the capabilities of pointers as alias, ASSOCIATE has the advantage of not having to worry about the POINTER and TARGET attributes and their implications. And you can also have nested constructs, associate names to expressions, and so on.