概述
ALLOCATABLE
一般在宣告陣列時必須指定大小,但有些問題在執行階段才知道需要多大的陣列,這時經常的解決辦法就是宣告一個足夠大的陣列,並告知使用者操作限制,如:
integer student(100), stu_count
print *,"輸入學生人數(MAX:100)"
read *, stu_count
do i = 1, stu_count
print *, "請輸入第",i,"位同學成績"
read *, student(i)
end do
...
Fortran 90則可以透過ALLOCATABLE來解決這個問題:
integer, allocatable :: student( ! 宣告一個可變大小的一維陣列
integer :: stu_count
print *,"輸入學生人數:"
read *, stu_count
allocate( student(stu_count) ) ! 配置stu_count個記憶體空間
do i = 1, stu_count
print *, "請輸入第",i,"位同學成績"
read *, student(i)
end do
...
-
宣告注意:
這裡需要 allocatable 和 allocate 兩個指令的配合,allocatable配合陣列宣告時使用,但陣列大小以「:」代替即可;當知道所需陣列大小時,再以 allocate 配置記憶體空間大小。 -
配置是否成功:
由於記憶體是有限的,不一定每次都會配置成功,如何得知是否配置成功?可寫成 allocate( student(stu_count), stat=error ) ,error是宣告好的整數變數,若成功,error傳為 0 ,其他數值表示失敗。 -
解除配置空間:
當該空間使用完畢,也可以透過 deallocate 指令來釋放配置空間:如:deallocate( student )
完整的語法如下:
DEALLOCATE ( object [, object] ...[, STAT=sv] )
-
object:
Is a structure component or the name of a variable, and must be a pointer or allocatable array. -
sv:
Is a scalar integer variable in which the status of the deallocation is stored.
-
-
多維陣列:
integer, allocatable :: stu_2(:,
! 兩個冒號代表二維陣列
integer, allocatable :: stu_3(:,:,
! 三個冒號代表三維陣列
allocate( stu_2(3,3) )
allocate( stu_2(4,4,4) )
-
指定索引座標範圍:
integer, allocatable :: stu_1(
integer, allocatable :: stu_2(:,
! 兩個冒號代表二維陣列
allocate( stu_1(-3:3) )
allocate( stu_2(-3:3,0:5) )
-
引自輔仁大學 技士及兼任講師林其盛
最后
以上就是清秀手套为你收集整理的Fortran中可变大小数组的定义的全部内容,希望文章能够帮你解决Fortran中可变大小数组的定义所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复