I'm sorry if this is a trivial question. My fortran-fu is poor.
Is there a way in Fortran to pass the array length? Using common
(which, from what I gather is equivalent to global
) is an option as well. What I want is in the main program to call a function with an array. For example (This is typed in, not copy pasted from anywhere)
program prog
integer num
double precision x(num),v
double precision test
....
v=test(x,num)
....
function test(x,num)
double precision test
integer num
double precision x(num)
test=0.0d0
....
return
end
This won't compile since num
is not a constant. The important thing is to know what the array size I'm passing is.
Edit: I'm using the GNU Fortran 95 compiler.
Edit2: I tried High Performance Mark's solution without luck:
program prog
integer v
parameter (v=10)
double precision x(v),test,k
k=test(x)
write (*,*) size(x)
stop
end
function test(x)
double precision, dimension(:),intent(in) :: x
double precision test
write (*,*) size(x)
test = 0.0d0
return
end
The output should be two lines where 10 is written. Instead I got this:
/scpc:niels: #$ f95 err.f
/scpc:niels: #$ ./a.out
0
10
/scpc:niels: #$
Fortran arrays 'know' how long they are, you shouldn't need to pass the array and its length as different arguments. (Unless, that is, you are interfacing with old Fortran codes.) Today you'd write something like this
function test(arr)
real, dimension(:), intent(in) :: arr
...
integer :: arrsize
...
arrsize = size(arr)
...
If you have to interface to old code in which array sizes are passed you can make calls like this
call old_fortran_subr(array, size(array, 1), other_arguments)
Oh, and while I'm writing, have nothing to do with common
in any code you write from scratch, it's a (rightly) deprecated feature from the 70's and earlier. Instead use module variables.