Appending arrays in Fortran [duplicate]

Solution 1:

Appending to or resizing arrays in Fortran is as simple as declaring them as an allocatable array,

integer, allocatable :: vecA(:), vecB(:), vecC(:)
character(*), parameter :: csv = "(*(g0,:,', '))"
vecA = [1,2,3]
vecB = [4,5,6]
vecC = [vecA, vecB]
write(*,csv) "vecA", vecA
write(*,csv) "vecB", vecB
write(*,csv) "vecC", vecC
vecC = [vecC, vecC(size(vecC):1:-1)]
write(*,csv) "vecC", vecC
end
vecA, 1, 2, 3
vecB, 4, 5, 6
vecC, 1, 2, 3, 4, 5, 6
vecC, 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1

The left-hand side is automatically resized to the proper length. Notice, how vecC = [vecC,vecC] doubles the length of vecC. If you have performance-critical code, you probably would want to avoid such automatic reallocations. But that becomes relevant only when the code is to be called on the order of billions of times.