Fortran Coder

查看: 9733|回复: 4
打印 上一主题 下一主题

[读物] 新人求助,《Fortran 95程序设计》书中关于指针的问题

[复制链接]

4

帖子

1

主题

0

精华

入门

F 币
29 元
贡献
18 点

规矩勋章

跳转到指定楼层
楼主
发表于 2015-11-27 15:57:02 | 显示全部楼层 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 dannybing 于 2015-11-27 15:57 编辑

在彭国伦老师的《Fortran 95程序设计》书中305页有一个利用串行读取学生成绩的程序,其中一段代码我不是很理解,向诸位求教。
[Fortran] 纯文本查看 复制代码
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

谢谢!
分享到:  微信微信
收藏收藏 点赞点赞 点踩点踩

4

帖子

1

主题

0

精华

入门

F 币
29 元
贡献
18 点

规矩勋章

沙发
 楼主| 发表于 2015-11-27 23:55:03 | 显示全部楼层
fcode 发表于 2015-11-27 18:50
null 是函数,用于返回一个空的指针。
nullify 是子程序,用于把一个指针置为空的指针。可以认为 a=>null() ...

谢谢解答!
那样就是说,作为一种好的编程习惯,程序中的指针无论是否需要访问,都最好为其分配指向(包括null),这么理解可以吗?

4

帖子

1

主题

0

精华

入门

F 币
29 元
贡献
18 点

规矩勋章

板凳
 楼主| 发表于 2015-11-29 10:50:28 | 显示全部楼层
fcode 发表于 2015-11-28 09:27
通常指针在定义以后会先设置为 null,如果指向的内容是分配的,还应该先释放,然后设置为 null
...

明白了!谢谢解答~
您需要登录后才可以回帖 登录 | 极速注册

本版积分规则

捐赠本站|Archiver|关于我们 About Us|小黑屋|Fcode ( 京ICP备18005632-2号 )

GMT+8, 2024-5-4 01:52

Powered by Tencent X3.4

© 2013-2024 Tencent

快速回复 返回顶部 返回列表