I'm writing a code that discretizes a circle and then gives back what points would be in an interval specified by the user. Using variables x,y, and theta, it writes the values of y and theta as they should be to the file info.dat, but writes that x is zero no matter what I do. It has no problem writing to points.dat either. Btw all variables were properly defined from the start as either allocatable, target, pointer, etc.
open(unit=2, file="points.DAT")
print*, 'Please enter the reference angle of the arc in degrees, number of points on the arc, and radius of the arc.'
read(*,*) a, n, r
a = a * pi / 180
allocate(x(1:n),y(1:n),theta(1:n))
do i = 1,n
theta(i:i) = a*(i-1)/n
x(i:i) = r * cos(theta(i:i))
y(i:i) = r * sin(theta(i:i))
xcoord(i:i) => x(i:i)
ycoord(i:i) => y(i:i)
angle(i:i) => theta(i:i)
write(2,*) 'x',i,'=',x(i:i),'y',i,'=',y(i:i), 'theta', i,'=', theta(i:i)
end do
deallocate(x,y,theta)
close(2)
open(unit=3, file="info.DAT")
print*, 'Please specify the interval of interest between 0 and 360 degrees'
read(*,*) b, c
b = b * pi / 180
c = c * pi / 180
do i = 1, n
if (any(b <= angle(i:i) .and. angle(i:i) <= c)) then
write(3,*) 'x', i, '=', xcoord(i:i), 'y', i, '=', ycoord(i:i), 'theta', i, '=', angle(i:i)
end if
end do
close(3)
Although you don't show it
xcoord ycoord angle
must be declared asPOINTER
. You set them to point to each single-element slice ofx() y() theta()
in turn, leave them pointing to the N'th elements, and then deallocate the underlying arrays so the pointers are now undefined (point to freed memory).If you have debugging options on your compiler (or possibly runtime) and use them, they should definitely detect the accesses to 1..n-1 while the pointer association is set to (n:n), and might detect that even (n) is invalid because of the deallocation. It appears by good luck the memory formerly used by
x
has been clobbered by something else but by bad lucky
andtheta
still have their values.