sai
sai

Reputation: 155

Change in a Fortran array results in change of another when using C pointers

I have C-type SIMD allocations using FFTW3 of two arrays f and g using the same plans. I have simply set f to 1, then g to f, then zeroed f. This also ends up zeroing g.

Why does this arise and what are some ways I can ensure that any derived arrays by slicing for example, don't get modified.

I would like f and g to point to two different blocks of two-dimensioanl double precision memory. I have not used the usual explicit shape (double precision, dimension(n,n)) definitions as the FFTW3 documentation states that arrays allocated in this manner are faster to deal with.

program main

use,intrinsic::iso_c_binding
implicit none
include 'fftw3.f03'

integer,parameter::n=16
real(C_DOUBLE),pointer::f(:,:),g(:,:)
type(C_PTR)::p

p=fftw_alloc_real(int(n**2,C_SIZE_T))
!i am thinking of these as FFTW plans that store only the stencil to
!allocate space starting from addresses given by real(C_DOUBLE),pointers above.

call c_f_pointer(p,f,[n,n])
call c_f_pointer(p,g,[n,n])

f=1.0d0
print*,sum(f)
g=f

f=0.0d0
print*,sum(g)

call fftw_free(p)
end program

The output is

256.00000000000000     
0.0000000000000000

Upvotes: 2

Views: 169

Answers (1)

francescalus
francescalus

Reputation: 32366

The allocation of memory is done by fftw_alloc_real. You call that only once, so only one block of memory is allocated. c_f_pointer does not perform any allocation.

c_f_pointer takes a C pointer and pointer associates a Fortran pointer with the target of the C pointer. When you

call c_f_pointer(p,f,[n,n])
call c_f_pointer(p,g,[n,n])

you are associating both f and g with the same lump of memory, that pointed to by p.

Simply allocate two distinct parts, with two calls to fftw_alloc_real and point f to one and g to the other.

Upvotes: 2

Related Questions