我是Fortran新手。我用Fortran 90編寫一個程序來得到一個數組的非零元素,並使用指針函數把它們放入一個新的數組如下:在編譯期間我fortran指針分配期間的90期望邊界規範
program prog
implicit none
integer, target :: a(5)
integer :: i
integer, pointer :: nz(:)
a(1) = 1
a(2) = 0
a(3) = 0
a(4) = 2
a(5) = 3
nz => non_zeros(a)
do i=1, size(nz)
write(*,*) nz(i)
end do
contains
function non_zeros(a)
integer, target :: a(:)
integer, pointer:: non_zeros(:)
integer :: n, i, j
n = count(a .ne. 0)
allocate(non_zeros(n))
j = 0
do i=1, m
if (a(i) .ne. 0) then
j = j + 1
non_zeros(j) => a(i)
end if
end do
end function non_zeros
end program prog
得到了錯誤:
non_zeros(j) => a(i)
1
Error: Expected bounds specification for 'non_zeros' at (1)
你能告訴我我做錯了什麼?先謝謝你!
更新我的問題:根據高性能馬克的解釋,我定義了一個派生類型:
program prog
implicit none
integer, target :: a(5)
type dt
integer, pointer :: x
end type
type(dt), allocatable :: nz(:)
a(1) = 1
a(2) = 0
a(3) = 0
a(4) = 2
a(5) = 3
nz = non_zeros(a)
contains
function non_zeros(a)
integer, target :: a(:)
type(dt), allocatable :: non_zeros(:)
integer :: n, i, j
n = count(a .ne. 0)
allocate(non_zeros(n))
j = 0
do i=1, m
if (a(i) .ne. 0) then
j = j + 1
non_zeros(j)%x => a(i)
end if
end do
end function non_zeros
end program prog
現在程序的工作,並給出了預期的效果。但是,在這種情況下,我沒有使用指針函數,因爲我的函數返回一個可分配的指針數組,而不是指向數組的指針。有什麼方法可以在這裏使用指針功能嗎?謝謝
我很懷疑您正嘗試在Fortran中編寫C語言(或類似的語言)。具有指針元素*的派生類型的*數組是常見的用於生成類似於指針數組的類似Fortran的技巧,但獲取包含「a」的非零元素的數組不是必需的。你寫的東西看起來很人性化,至少這個Fortran程序員是不自然的。 –
@HighPerformanceMark正如我所說,我是Fortran的新手,我曾經在Python上工作。這就是爲什麼該程序看起來不自然。您可以請作爲Fortran的專家提示我如何更改我的代碼,以便它將成爲自然的Fortran程序!非常感謝 –
我回答了您的問題*我正在編寫Fortran 90中的程序,以獲取數組中的非零元素,並在我的第一個響應(下)中將它們放入一個新數組*中。我看到沒有必要爲此使用指針。 –