memory management - Read array of unknown size from keyboard -
i want insert unknown number of values in array (no matter order). first read how many values inserted, allocate allocatable array, , read values, in following code
program try implicit none integer :: n real, dimension(:), allocatable :: x write (*,*) "how many values?" read (*,*) n allocate(x(n)) write (*,*) "insert values" read (*,*) x end program
what if want insert values without declaring how many before allocating array? think should use while cycle insert values in ascending order, till descending value insert, indicating sequence ended. think part of code following,
index = 1 write(*,*) x read(*,*) x(index) exit = .false. while (exit.eqv..false.) index = index + 1 read(*,*) x(index) if (x(index)>x(index-1)) exit = .true. index = index - 1 end if end
how declare array x
?
i tried following solution, building on concept "a lot of memory allocation , reallocation" expressed @high performance mark.
program coeffs use compact implicit none real, dimension(:), allocatable :: x,x2 integer :: nl,nr,nt,index,ol,or logical :: exit write(*,*) "input increasing sequence of reals (end sequence & & first decreasing element, discarded):" index = 1 allocate(x(index)) read(*,*) x(index) allocate(x2(index)) x2 = x deallocate(x) exit = .false. while (exit.eqv..false.) index = index + 1 allocate(x(index)) x(1:index-1) = x2 read(*,*) x(index) deallocate(x2) allocate(x2(index)) x2 = x deallocate(x) if (x2(index)<x2(index-1)) exit = .true. index = index - 1 allocate(x(index)) x = x2(1:index) end if end deallocate(x2) write(*,*) "x = ", x end program
with array being input keyboard, don't think allocation/reallocation problem, since happens @ higher speed of fingers typing values, doesn't it? still think code made better. instance, using 2 arrays way take advantage of allocation/reallocation?
Comments
Post a Comment