新人求助,《Fortran 95程序设计》书中关于指针的问题
本帖最后由 dannybing 于 2015-11-27 15:57 编辑在彭国伦老师的《Fortran 95程序设计》书中305页有一个利用串行读取学生成绩的程序,其中一段代码我不是很理解,向诸位求教。
module linklist
type student
integer::num,Chi,Eng,Math,Sci,Sol
end type
type datalink
type(student)::item
type(datalink),pointer::next
end type
contains
function SearchList(num,head)
implicit none
integer::num
type(datalink),pointer::head,p
type(datalink),pointer::SearchList
p=>head
nullify(SearchList)
do while(associated(p))
if(p%item%num==num)then
SearchList=>p
return
end if
p=>p%next
end do
return
end function
end module linklist
program ex1016
use linklist
implicit none
character(len=20)::filename
character(len=80)::tempstr
type(datalink),pointer::head
type(datalink),pointer::p
integer i,error,size
write(*,*)"filename:"
read(*,*)filename
open(10,file=filename,status="old",iostat=error)
if(error/=0)then
write(*,*)"open file fail"
stop
end if
allocate(head)
!nullify(head%next)
p=>head
size=0
read(10,"(A80)")tempstr
do while(.true.)
read(10,fmt=*,iostat=error)p%item
if(error/=0)exit
size=size+1
allocate(p%next,stat=error)
if(error/=0)then
write(*,*)"out of memory"
stop
end if
p=>p%next
!nullify(p%next)
end do
write(*,"('共有',I3,'位学生')")size
do while(.true.)
write(*,*)"要查询几号同学的成绩?"
read(*,*)i
if(i<1.or.i>size)exit
p=>SearchList(i,head)
if(associated(p))then
write(*,"(5(A6,I3))")"中文",p%item%Chi,"英文",p%item%Eng,&
"数学",p%item%Math,"自然",p%item%Sci,"社会",p%item%Sol
else
exit
end if
end do
write(*,"('座号',I3,'不存在,程序结束')")i
stop
end program
请问其中被注释掉的两个nullify函数在程序中具体起到什么作用?即使注释掉之后也不会影响程序运行
书中278页中有指出,null及nullify可以将指针指向一个不可使用的内存,从而避免associated判断时报错,在此程序中是否也是这一作用?
编译工具为IVF
谢谢!
null 是函数,用于返回一个空的指针。
nullify 是子程序,用于把一个指针置为空的指针。可以认为 a=>null() 和 nullify(a) 是一样的
指针在定义以后,其指向的内容是不确定的,可能指向空,也可能指向随机的位置。如果此时直接访问指针,则可能出现内存违例。
尽管在某些编译器上,指针一开始定义就可能指向空,但不能保证所有环境都这样。所以最好手动设置为空指针。
其实这个问题,与变量初值是 0 ,是非常类似的。 fcode 发表于 2015-11-27 18:50
null 是函数,用于返回一个空的指针。
nullify 是子程序,用于把一个指针置为空的指针。可以认为 a=>null() ...
谢谢解答!
那样就是说,作为一种好的编程习惯,程序中的指针无论是否需要访问,都最好为其分配指向(包括null),这么理解可以吗? 通常指针在定义以后会先设置为 null,如果指向的内容是分配的,还应该先释放,然后设置为 null
fcode 发表于 2015-11-28 09:27
通常指针在定义以后会先设置为 null,如果指向的内容是分配的,还应该先释放,然后设置为 null
...
明白了!谢谢解答~
页:
[1]