How to write using subroutine?

How to write using subroutine?

program main
implicit none
! compile : ifort /assume:realloc_lhs main.f90
integer,allocatable :: a(:), b(..)
integer :: val = 20
integer :: pos = 2
integer :: i,j

a = [a,[10, 20, 40, 50]]
write(*,* ) “a array:”, a,size(a)
!----------------------------------
do i = 1, size(a)
if (i /= pos .and. a(i) /= val) then
!write(*, *) a(i)
b=[b,a(i)]
end if
end do
!------------------------------------

write(*,* ) “b array:”, b

end program main

this program is working , but if I use subroutine , do not work

program main

implicit none

integer,allocatable :: a(:),b(:)
integer :: val = 20
integer :: pos = 2
integer :: i,j

a = [a,[10, 20, 40, 50]]
write(*,* ) “a dizisi:”, a,size(a)
call extract(a,b,val,pos)

write(*,* ) “b dizisi:”, b

end program main

subroutine extract(a,b,val,pos)
implicit none
integer,allocatable :: a(:),b(..)
integer::val,pos
integer::i
write(*,*) a
do i = 1, size(a)
if (i /= pos .and. a(i) /= val) then
write(*,* ) a(i)
b=[b,a(i)]
end if
end do

end subroutine extract

Create TopicClose

In your code, do you really mean to write b(..) rather than b(:)? Also, the subroutine should be put in a module since it has an assumed shape argument.

Does this meet your expectations?

module mod_extract
   implicit none
   
   private
   public :: extract
   
contains

   subroutine extract(a, b, val, pos)
      integer, intent(in)               :: a(:)
      integer, intent(in)               :: val, pos
      integer, intent(out), allocatable :: b(:)
      integer                           :: i

       b = pack(a, [(i /= pos .and. a(i) /= val, i = 1, size(a))])
   end subroutine extract

end module mod_extract
program main
   use mod_extract
   implicit none
   
   integer, allocatable :: a(:), b(:)
   
   allocate(a(4))
   a = [10, 20, 40, 50]
   call extract(a, b, 20, 2)
   print*, "a:", a
   print*, "b:", b
   deallocate(a, b)
end program main

Results:

 a:          10          20          40          50
 b:          10          40          50
1 Like

Thank you very much for telling how to write array b(:slight_smile: