1

I created a program to generate an array (1,2,3,4,5) in Fortran, from within a function. I know it can be done much easier, but I'd like to know why what I did does not work.

program main
  implicit none
  integer, dimension(5) :: array1, fillArray

  array1 = fillArray  
  print*,array1

end program main

function fillArray()
    implicit none
    integer :: i
    integer, dimension(5) :: fillArray

    do i = 1,5
        fillArray(i) = i
    end do
end function fillArray

When compiled this returns 0 0 -2146721293 1 0

I thought perhaps I needed to define it like array1 = fillArray(). That doesn't work either.

Passing in a useless variable a like this:

program main
  implicit none
  integer, dimension(5) :: array1, fillArray

  array1 = fillArray(4) 
  print*,array1

end program main

function fillArray(a)
    implicit none
    integer :: i,a
    integer, dimension(5) :: fillArray
    a = a+1
    do i = 1,5
        fillArray(i) = i
    end do
end function fillArray

Gives

1 1 1 1 1

In conclusion, I have no idea what is going on. I did look at similar questions, but I am not experienced enough with Fortran to reproduce my result using other sample code.

*edit: I am surprised this was already asked since I sifted through the site for quite some time and I couldn't find it. But my problem is solved now, thanks for the reply!

*edit2: For the record, the solution was:

module mySubs !modules before the program!
    implicit none

    contains

    function fillArray()

        integer :: i
        integer, dimension(5) :: fillArray

        do i = 1,5
            fillArray(i) = i
        end do
    end function fillArray

end module mySubs

program main
    use mySubs
    implicit none
    integer, dimension(5) :: array1

    array1 = fillArray() 
    print*,array1

end program main
  • You are missing an explicit for the function. Functions returning arrays require explicit interface. That can be done by using modules or by making the function internal. The two linked questions and answers explain it in details. In your case `integer, dimension(5) :: array1, fillArray` defines a new local array in the main program, not the function, – Vladimir F Героям слава Apr 14 '17 at 19:38
  • It is not too easy to find the duplicates, you must know what to look for. – Vladimir F Героям слава Apr 14 '17 at 19:46

0 Answers0