The caveat, per the Fortran standard, is there is no stipulation there be a companion C processor but the use of c_loc
will require as such.
But now when a companion C processor is on hand, the easier approach will be to use C_ASSOCIATED
function defined in the intrinsic module ISO_C_BINDING
:
use iso_c_binding, only: c_loc, c_ptr, c_associated, c_size_t
integer, allocatable, target :: a(:)
type(c_ptr) :: p1, p2
integer(c_size_t) :: i
a = [ 1 ]
p1 = c_loc(a)
print "(g0,z0)", "Address of a (hex) following initial allocation: ", &
transfer( p1, mold=i )
a = [ a, [ 2, 3 ] ]
p2 = c_loc(a)
print "(g0,z0)", "Address of a (hex) following reallocation: ", &
transfer( p2, mold=i )
print *, "c_associated(p1, p2)?", c_associated(p1, p2)
end
Note the response from 2 different compilers: with gfortran where you get a C realloc
kind of behavior and the other with IFORT where you don;'t:
C:\temp>ifort /standard-semantics a.f90
Intel(R) Fortran Intel(R) 64 Compiler Classic for applications running on Intel(R) 64, Version 2021.2.0 Build 20210228_000000
Copyright (C) 1985-2021 Intel Corporation. All rights reserved.
Microsoft (R) Incremental Linker Version 14.27.29112.0
Copyright (C) Microsoft Corporation. All rights reserved.
-out:a.exe
-subsystem:console
a.obj
C:\temp>a.exe
Address of a (hex) following initial allocation: 267DA1A6890
Address of a (hex) following reallocation: 267DA1A63B0
c_associated(p1, p2)? F
C:\temp>gfortran a.f90 -o gcc-a.exe
C:\temp>gcc-a.exe
Address of a (hex) following initial allocation: 793A40
Address of a (hex) following reallocation: 793A40
c_associated(p1, p2)? T
C:\temp>