I need an array of variable sizes in Fortran. In C ++, I would use a vector. Therefore, I have a function like
integer function append(n, array, value) integer, pointer, dimension(:) :: array integer, pointer, dimension(:) :: tmp_arr integer n if (size(array) .eq. n) then allocate(tmp_arr(2*size(array))) tmp_arr(1:size(array)) = array deallocate(array) array => tmp_arr end if n = n + 1 array(n) = value append = n end function
which works great if i use it in a way
integer pos, val pos = append(n, array, val)
However, if I would like to use it in a way
integer i,j,n ! i,j<n array(i) = append(n, array, array(j))
with gfortran it does not work. It compiles, but segfaults. The problem is that gfortran makes addresses from array (i) and array (j), sends the latter to the append function, and then when the address of array (j) is accessed and one of array (i) is written, the address space has been freed .
I would like the value of array (j) to be pushed onto the stack (rather than the address), and then used in the function, and after the function has finished, the uptodate address of array (i) is looked up and the result of the stored function.
I'm sure gcc will do it the way I want, why is gfortran so boring?
Is there any way in Fortran to make it reliable (which means an example of an array (j) = ...) of a function or data type to have a C ++ stl vector as a behavior?
Conclusion:
I ended up introducing temporary variables
integer tmp_val tmp_val = value ... array(n) = tmp_val
therefore, at least the method can be called
pos = append(n, array, array(j)) array(i) = pos
and hope that other / future project developers will not try to βoptimizeβ the two lines to eliminate the need for βpos.β
Thanks for the answers and comments.