How to add new element to dynamical array in Fortran90

送分小仙女□ 提交于 2019-12-06 06:10:28

I suspect, looking at an artefact, that you noticed the problem - but quickly moved on.

The suspicious line, to me is:

    allocate(clist(isize+2))

Why isn't the new size isize+1? I guess that you tried that, but then the program failed.

Seeing why the program failed (possibly crashed) is key to why you aren't getting the correct result. Look closely at the loop (print statement removed for clarity).

do i=1,isize
    clist(i) = list(i)
end do
clist(i+1) = element

You want to say "copy all elements from list to clist, then append element". Which is correct. However

do i=1,isize
    clist(i) = list(i)
end do
! Here, i=isize+1
clist(i+1) = element
! Which means
! clist(isize+2) = element.

In summary, after the loop the loop index variable doesn't have the value it had in the final iteration.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!