How can I access the array by its storage address

How can I access the array by its storage address

Hello,

       I have a question about the usages of function loc or c_loc.

I want to access the array a in a subroutine. 

I konw that the loc or c_loc can gets the storage address of the variable.

But how to use its address to access its data .( not using 'use datamod')

In the C language , I can manage it. Can we do it in Fortran.

      Thanks in advance!

!-----------------------------------------
module datamod
!-----------------------------------------
implicit none
!
   real,allocatable,save :: a(:)
   real,allocatable,save :: b(:,:)
!  
end module datamod

!-----------------------------------------
program main
!-----------------------------------------
use datamod
implicit none
integer :: i
integer :: loc_a,loc_b
!
!allocate a ----------------------------------------
!
allocate(a(10))
do i=1,10
 a(i) = real(i)
end do
!
! get the address of a
loc_a = loc(a)
write(*,*) 'the address of a storage',loc_a
!
! how can I get the data of array 'a' by its address
!
end program

publicaciones de 3 / 0 nuevos
Último envío
Para obtener más información sobre las optimizaciones del compilador, consulte el aviso sobre la optimización.
Best Reply

The standard way to do this:


	program main

	!-----------------------------------------

	use datamod

	use, intrinsic :: iso_c_binding

	implicit none

	integer :: i

	type(c_ptr) :: loc_a

	real, pointer :: ap(:)
!

	!allocate a ----------------------------------------

	!

	allocate(a(10))

	do i=1,10

	 a(i) = real(i)

	end do

	!

	! get the address of a

	loc_a = c_loc(a)

	write(*,*) 'the address of a storage',loc_a

	!

	! how can I get the data of array 'a' by its address

	!

	call c_f_pointer(loc_a, ap, [10])

	print *, ap

	end program

In this case I have used c_loc. If you want to use an integer to hold the address, you must declare it as integer(c_intptr_t) where c_intptr_t comes from module iso_c_binding. You can also use integer(int_ptr_kind()). If you use an integer pointer, replace loc_a in the call to c_f_pointer with transfer(loc_a, c_null_ptr).

Steve - Intel Developer Support

Thanks for your answer.

Deje un comentario

Por favor inicie sesión para agregar un comentario. ¿No es socio? Únase ya